-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdeno.ts
56 lines (48 loc) · 1.34 KB
/
deno.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
/**
* Author: netnr
* Date: 2022-10
*
* deno run --allow-net --allow-read --watch deno.ts
*/
import { serve } from "https://deno.land/[email protected]/http/server.ts";
import { lookup } from "https://deno.land/x/[email protected]/mod.ts";
serve(handler, { port: 713 });
async function handler(req: Request): Promise<Response> {
let filePath = "." + new URL(req.url).pathname;
if (filePath.endsWith("/")) {
filePath += "index.html";
}
let fileSize;
try {
fileSize = (await Deno.stat(filePath)).size;
} catch (e) {
if (e instanceof Deno.errors.NotFound) {
try {
filePath = "./404.html";
fileSize = (await Deno.stat(filePath)).size;
} catch (err) {
return new Response("404", { status: 404 });
}
} else {
return new Response("500", { status: 500 });
}
}
const body = await Deno.readFile(filePath);
let contentType = lookup(filePath) || "application/octet-stream";
// charset
if (
contentType.startsWith("text/") ||
contentType.endsWith("/json") ||
contentType.endsWith("/javascript") ||
contentType.endsWith("/xml")
) {
contentType = `${contentType}; charset=utf-8`;
}
return new Response(body, {
headers: {
"content-length": fileSize.toString(),
"content-type": contentType,
"access-control-allow-origin": "*",
},
});
}