1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-11-27 16:10:57 -05:00
denoland-deno/http.ts
Ryan Dahl 0d048b8704 Init
Original: 60735e1804
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;
}