aboutsummaryrefslogtreecommitdiff
path: root/v_windows/v/old/vlib/net/http/server.v
diff options
context:
space:
mode:
authorIndrajith K L2022-12-03 17:00:20 +0530
committerIndrajith K L2022-12-03 17:00:20 +0530
commitf5c4671bfbad96bf346bd7e9a21fc4317b4959df (patch)
tree2764fc62da58f2ba8da7ed341643fc359873142f /v_windows/v/old/vlib/net/http/server.v
downloadcli-tools-windows-master.tar.gz
cli-tools-windows-master.tar.bz2
cli-tools-windows-master.zip
Adds most of the toolsHEADmaster
Diffstat (limited to 'v_windows/v/old/vlib/net/http/server.v')
-rw-r--r--v_windows/v/old/vlib/net/http/server.v80
1 files changed, 80 insertions, 0 deletions
diff --git a/v_windows/v/old/vlib/net/http/server.v b/v_windows/v/old/vlib/net/http/server.v
new file mode 100644
index 0000000..3804ae3
--- /dev/null
+++ b/v_windows/v/old/vlib/net/http/server.v
@@ -0,0 +1,80 @@
+// Copyright (c) 2019-2021 Alexander Medvednikov. All rights reserved.
+// Use of this source code is governed by an MIT license
+// that can be found in the LICENSE file.
+module http
+
+import io
+import net
+import time
+
+interface Handler {
+ handle(Request) Response
+}
+
+pub struct Server {
+pub mut:
+ port int = 8080
+ handler Handler = DebugHandler{}
+ read_timeout time.Duration = 30 * time.second
+ write_timeout time.Duration = 30 * time.second
+}
+
+pub fn (mut s Server) listen_and_serve() ? {
+ if s.handler is DebugHandler {
+ eprintln('Server handler not set, using debug handler')
+ }
+ mut l := net.listen_tcp(.ip6, ':$s.port') ?
+ eprintln('Listening on :$s.port')
+ for {
+ mut conn := l.accept() or {
+ eprintln('accept() failed: $err; skipping')
+ continue
+ }
+ conn.set_read_timeout(s.read_timeout)
+ conn.set_write_timeout(s.write_timeout)
+ // TODO: make concurrent
+ s.parse_and_respond(mut conn)
+ }
+}
+
+fn (mut s Server) parse_and_respond(mut conn net.TcpConn) {
+ defer {
+ conn.close() or { eprintln('close() failed: $err') }
+ }
+
+ mut reader := io.new_buffered_reader(reader: conn)
+ defer {
+ reader.free()
+ }
+ req := parse_request(mut reader) or {
+ $if debug {
+ // only show in debug mode to prevent abuse
+ eprintln('error parsing request: $err')
+ }
+ return
+ }
+ mut resp := s.handler.handle(req)
+ if resp.version() == .unknown {
+ resp.set_version(req.version)
+ }
+ conn.write(resp.bytes()) or { eprintln('error sending response: $err') }
+}
+
+// DebugHandler implements the Handler interface by echoing the request
+// in the response
+struct DebugHandler {}
+
+fn (d DebugHandler) handle(req Request) Response {
+ $if debug {
+ eprintln('[$time.now()] $req.method $req.url\n\r$req.header\n\r$req.data - 200 OK')
+ } $else {
+ eprintln('[$time.now()] $req.method $req.url - 200')
+ }
+ mut r := Response{
+ text: req.data
+ header: req.header
+ }
+ r.set_status(.ok)
+ r.set_version(req.version)
+ return r
+}