-
-
Notifications
You must be signed in to change notification settings - Fork 38
/
serve_static.ts
78 lines (76 loc) 路 2.59 KB
/
serve_static.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
// Copyright 2019 Yusuke Sakurai. All rights reserved. MIT license.
import * as path from "./vendor/https/deno.land/std/path/mod.ts";
import * as media_types from "./vendor/https/deno.land/std/media_types/mod.ts";
import { resolveIndexPath } from "./matcher.ts";
import { ServeHandler } from "./server.ts";
export type ServeStaticOptions = {
/**
* Custom Content-Type mapper.
* .ext -> application/some-type
* By default, .ts/.tsx will be resolved by application/typescript.
*/
contentTypeMap?: Map<string, string>;
/**
* Custom Content-Disposition mapper.
* .ext -> "inline" | "attachment"
* By default, Content-Disposition header won't be set for any files.
*/
contentDispositionMap?: Map<string, "inline" | "attachment">;
/** Custom filter function for files */
filter?: (file: string) => boolean | Promise<boolean>;
};
/**
* Serve static files in specified directory.
* */
export function serveStatic(
dir: string,
opts: ServeStaticOptions = {},
): ServeHandler {
const contentTypeMap = new Map<string, string>([
[".ts", "application/javascript"],
[".tsx", "application/javascript"],
...(opts.contentTypeMap || new Map<string, string>()).entries(),
]);
const contentDispositionMap = opts.contentDispositionMap || new Map([]);
const filter = opts.filter || (() => true);
return async function serveStatic(req) {
if (req.method === "GET" || req.method === "HEAD") {
const filepath = await resolveIndexPath(
dir,
decodeURIComponent(req.path),
);
if (!filepath || !(await filter(filepath))) {
return;
}
const stat = await Deno.stat(filepath);
const ext = path.extname(filepath);
const base = path.basename(filepath);
let contentType = contentTypeMap.get(ext) ||
media_types.contentType(ext) ||
"application/octet-stream";
const headers = new Headers({
"content-length": stat.size + "",
"content-type": contentType,
});
const contentDisposition = contentDispositionMap.get(ext);
if (contentDisposition === "attachment") {
headers.set("content-disposition", `attachment; filename="${base}"`);
} else if (contentDisposition === "inline") {
headers.set("content-disposition", "inline");
}
if (req.method === "HEAD") {
return req.respond({
status: 200,
headers,
});
} else {
const file = await Deno.open(filepath, "r");
try {
await req.respond({ status: 200, headers, body: file });
} finally {
file.close();
}
}
}
};
}