1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-12-11 18:17:48 -05:00
denoland-deno/http.ts
Ryan Dahl 60735e1804 Init
2018-11-07 01:12:48 -05:00

42 lines
863 B
TypeScript

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;
}