From 60735e18043b54f51cf794ebe152459d5e066e6d Mon Sep 17 00:00:00 2001 From: Ryan Dahl Date: Wed, 7 Nov 2018 01:08:51 -0500 Subject: [PATCH] Init --- http.ts | 42 ++++++++++++++++++++++++++++++++++++++++++ http_test.ts | 4 ++++ 2 files changed, 46 insertions(+) create mode 100644 http.ts create mode 100644 http_test.ts diff --git a/http.ts b/http.ts new file mode 100644 index 000000000..d4c496e15 --- /dev/null +++ b/http.ts @@ -0,0 +1,42 @@ +import * as deno from "deno"; + +class Server { + _closing = false; + + constructor(readonly listener: deno.Listener) {} + + async serveConn(conn: deno.Conn) { + const buffer = new Uint8Array(1024); + try { + while (true) { + const r = await conn.read(buffer); + if (r.eof) { + break; + } + const response = new TextEncoder().encode( + "HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello World\n" + ); + await conn.write(response); + } + } finally { + conn.close(); + } + } + + async serve() { + while (!this._closing) { + const conn = await this.listener.accept(); + this.serveConn(conn); + } + } + + close() { + this._closing = true; + } +} + +export function listen(addr: string): Server { + const listener = deno.listen("tcp", addr); + const s = new Server(listener); + return s; +} diff --git a/http_test.ts b/http_test.ts new file mode 100644 index 000000000..32c868ad5 --- /dev/null +++ b/http_test.ts @@ -0,0 +1,4 @@ +import { listen } from "./server.ts"; + +const s = listen("0.0.0.0:4500"); +s.serve();