-
Notifications
You must be signed in to change notification settings - Fork 170
/
serve.ts
112 lines (100 loc) · 3.43 KB
/
serve.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
import { readableStreamFromReader } from "https://deno.land/std@0.136.0/streams/conversion.ts";
import { basename, join } from "https://deno.land/std@0.136.0/path/mod.ts";
import { Server, type ServerInit } from "https://deno.land/std@0.136.0/http/server.ts";
import { getContentType } from "./mime.ts";
export type ServeInit = ServerInit & {
certFile?: string;
keyFile?: string;
signal?: AbortSignal;
onListenSuccess?: (port: number) => void;
};
export async function serve(options: ServeInit) {
const server = new Server(options);
let port: number;
let listener: Deno.Listener;
if (options.certFile && options.keyFile) {
port = options.port ?? 443;
listener = Deno.listenTls({
port,
hostname: options.hostname ?? "0.0.0.0",
certFile: options.certFile,
keyFile: options.keyFile,
transport: "tcp",
// ALPN protocol support not yet stable.
// alpnProtocols: ["h2", "http/1.1"],
});
} else {
port = options.port ?? 80;
listener = Deno.listen({
port,
hostname: options.hostname ?? "0.0.0.0",
transport: "tcp",
});
}
options?.signal?.addEventListener("abort", () => server.close(), {
once: true,
});
options.onListenSuccess?.(port);
await server.serve(listener);
}
export type ServeDirOptions = Omit<ServeInit, "handler"> & {
workingDir?: string;
loader?: (req: Request) => Promise<{ content: string | Uint8Array; contentType?: string } | null | undefined>;
};
export async function serveDir(options: ServeDirOptions) {
const workingDir = options.workingDir || Deno.cwd();
const handler = async (req: Request): Promise<Response> => {
const url = new URL(req.url);
const filepath = join(workingDir, url.pathname);
try {
const stat = await Deno.lstat(filepath);
if (stat.isDirectory) {
const title = basename(workingDir) + url.pathname;
const items: string[] = [];
for await (const item of Deno.readDir(filepath)) {
if (!item.name.startsWith(".")) {
items.push(
`<li><a href='${join(url.pathname, encodeURI(item.name))}'>${item.name}${
item.isDirectory ? "/" : ""
}<a></li>`,
);
}
}
return new Response(
`<!DOCTYPE html><title>${title}</title><h2> ${title}</h2><ul>${Array.from(items).join("")}</ul>`,
{
headers: {
"Content-Type": "text/html; charset=utf-8",
"Cache-Control": "no-cache, no-store, must-revalidate",
},
},
);
}
if (options.loader) {
const ret = await options.loader(req);
if (ret) {
return new Response(ret.content, {
headers: {
"Content-Type": ret.contentType || getContentType(filepath),
"Last-Modified": stat.mtime?.toUTCString() || "",
},
});
}
}
const file = await Deno.open(filepath, { read: true });
return new Response(readableStreamFromReader(file), {
headers: {
"Content-Type": getContentType(filepath),
"Last-Modified": stat.mtime?.toUTCString() || "",
},
});
} catch (err) {
if (err instanceof Deno.errors.NotFound) {
return new Response("Not found", { status: 404 });
}
console.error(err.stack);
return new Response(err.message, { status: 500 });
}
};
await serve({ ...options, handler });
}