1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-12-03 17:08:35 -05:00
denoland-deno/http.ts

73 lines
1.7 KiB
TypeScript
Raw Normal View History

2018-11-07 01:08:51 -05:00
import * as deno from "deno";
2018-11-07 13:16:07 -05:00
import * as bufio from "./bufio.ts";
import { TextProtoReader } from "./textproto.ts";
type Handler = (req: ServerRequest) => Promise<void>;
2018-11-07 01:08:51 -05:00
class Server {
_closing = false;
constructor(readonly listener: deno.Listener) {}
2018-11-07 13:16:07 -05:00
async serve(handler: Handler) {
while (!this._closing) {
const c = await this.listener.accept();
const sc = new ServerConn(c);
sc.serve(handler);
}
}
close() {
this._closing = true;
this.listener.close();
}
}
class ServerConn {
constructor(readonly c: deno.Conn) {
// TODO Use memory pool to obtain bufr and bufw.
this.bufr = new bufio.Reader(c);
this.bufw = new bufio.Writer(c);
}
async serve(handler: Handler): Promise<void> {
2018-11-07 01:08:51 -05:00
const buffer = new Uint8Array(1024);
try {
while (true) {
2018-11-07 13:16:07 -05:00
const req = readRequest(this.bufr);
/*
2018-11-07 01:08:51 -05:00
const response = new TextEncoder().encode(
"HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello World\n"
);
2018-11-07 13:16:07 -05:00
await this.c.write(response);
*/
2018-11-07 01:08:51 -05:00
}
} finally {
2018-11-07 13:16:07 -05:00
this.c.close();
2018-11-07 01:08:51 -05:00
}
}
2018-11-07 13:16:07 -05:00
}
2018-11-07 01:08:51 -05:00
2018-11-07 13:16:07 -05:00
function readRequest(b: bufio.Reader): ServerRequest {
const tp = new TextProtoReader(b);
const req = new ServerRequest();
2018-11-07 01:08:51 -05:00
2018-11-07 13:16:07 -05:00
// First line: GET /index.html HTTP/1.0
const s = await tp.readLine();
const [ method, url, proto ] = parseRequestLine(s);
console.log("readRequest", method, url);
}
// Returns [method, url, proto]
function parseRequestLine(line: string): [ string, string, string ] {
return line.split(" ", 3);
2018-11-07 01:08:51 -05:00
}
export function listen(addr: string): Server {
const listener = deno.listen("tcp", addr);
const s = new Server(listener);
return s;
}
2018-11-07 13:16:07 -05:00