summaryrefslogtreecommitdiff
path: root/http.ts
blob: c7ac888796b54608524cee3f631223fc0608d366 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import { listen, Conn } from "deno";
import { BufReader, BufState } from "./bufio.ts";
import { TextProtoReader } from "./textproto.ts";
import { Headers } from "./headers.ts";

export async function* serve(addr: string) {
  const listener = listen("tcp", addr);
  while (true) {
    const c = await listener.accept();
    yield* serveConn(c);
  }
  listener.close();
}

export async function* serveConn(c: Conn) {
  let bufr = new BufReader(c);
  try {
    while (true) {
      const req = await readRequest(bufr);
      yield req;
    }
  } finally {
    c.close();
  }
}

interface Response {
  status?: number;
  body: string;
}

class ServerRequest {
  url: string;
  method: string;
  proto: string;

  respond(r: Response = { status: 200 }): Promise<void> {
    throw Error("not implemented");
  }
}

async function readRequest(b: BufReader): Promise<ServerRequest> {
  const tp = new TextProtoReader(b);
  const req = new ServerRequest();

  // First line: GET /index.html HTTP/1.0
  let s: string;
  let err: BufState;
  [s, err] = await tp.readLine();
  const { method, url, proto } = parseRequestLine(s);
  req.method = method;
  req.url = url;
  req.proto = proto;

  let headers: Headers;
  [headers, err] = await tp.readMIMEHeader();

  return req;
}

// Returns [method, url, proto]
function parseRequestLine(
  line: string
): { method: string; url: string; proto: string } {
  let [method, url, proto] = line.split(" ", 3);
  return { method, url, proto };
}