-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.ts
46 lines (43 loc) · 1.13 KB
/
server.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
// eslint-disable-next-line max-len, no-unused-vars
export type RequestEventHandler = (request: Request) => Response | Promise<Response>;
export function serveHttp (
requestEventHandler: RequestEventHandler,
listenOptions?: Partial<Deno.ListenOptions>,
): {
listener: Deno.Listener;
url: URL;
} {
const hostname = listenOptions?.hostname ?? '0.0.0.0';
// eslint-disable-next-line no-magic-numbers
const port = listenOptions?.port ?? 80;
const listener = Deno.listen({hostname, port});
(async () => {
try {
for await (const conn of listener) {
(async () => {
try {
const httpConn = Deno.serveHttp(conn);
for await (const {request, respondWith} of httpConn) {
try {
respondWith(requestEventHandler(request));
}
catch (ex) {
console.error(ex);
}
}
}
catch (ex) {
console.error(ex);
}
})();
}
}
catch (ex) {
console.error(ex);
}
})();
return {
listener,
url: new URL(`http://${hostname}:${port}/`),
};
}