-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
89 lines (76 loc) · 2.13 KB
/
index.ts
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import {
serve,
ServerRequest,
} from "https://deno.land/[email protected]/http/server.ts";
import * as path from "https://deno.land/[email protected]/path/mod.ts";
import { acceptWebSocket } from "https://deno.land/[email protected]/ws/mod.ts";
import { handleWs } from "./handleWs.ts";
const staticMatch: Set<string> = new Set();
function walkStaticFiles(root: string) {
for (const f of Deno.readDirSync(path.resolve(Deno.cwd(), root))) {
const c = path.join(root, f.name);
if (f.isFile) {
staticMatch.add(c);
} else if (f.isDirectory) {
walkStaticFiles(c);
}
}
}
walkStaticFiles("static");
console.log("Static files: ", staticMatch);
type MiddlewarePayload = {
url: URL;
req: ServerRequest;
};
type MiddlewareFn = (options: MiddlewarePayload) => Promise<true | undefined>;
const index: MiddlewareFn = async ({ url, req }: MiddlewarePayload) => {
if (url.pathname === "/") {
req.respond({
body: await Deno.readFile(path.resolve(Deno.cwd(), "static/index.html")),
});
return true;
}
};
const staticFiles: MiddlewareFn = async ({ url, req }) => {
// remove head slash
const fname = url.pathname.slice(1);
if (staticMatch.has(fname)) {
req.respond({
body: await Deno.readFile(path.resolve(Deno.cwd(), fname)),
});
return true;
}
};
const wsMiddleware: MiddlewareFn = async ({ url, req }) => {
if (url.pathname === "/connect") {
const sock = await acceptWebSocket({
conn: req.conn,
bufReader: req.r,
bufWriter: req.w,
headers: req.headers,
});
handleWs(sock);
return true;
}
};
const combineProcessors =
(...fns: MiddlewareFn[]) =>
async (options: MiddlewarePayload) => {
for (const fn of fns) {
const result = await fn(options);
if (result) {
return result;
}
}
};
const processors = combineProcessors(index, staticFiles, wsMiddleware);
const server = serve({ port: 3000 });
console.log("Listening on 3000");
const BASE = "http://localhost";
for await (const req of server) {
const url = new URL(req.url, BASE);
const result = await processors({ url, req });
if (!result) {
req.respond({ status: 404 });
}
}