-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
static.ts
47 lines (42 loc) · 1.1 KB
/
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
import { Status, STATUS_TEXT } from "./deps.ts";
export async function handleStaticFile(
reqUrl: string,
staticURL: string,
maxAge: number,
) {
let file;
const path = getPathUrl(reqUrl, staticURL);
if (!path) {
return new Response(STATUS_TEXT[Status.NotFound], {
status: Status.NotFound,
});
}
try {
file = await Deno.open(`.${path}`, { read: true });
} catch (error) {
console.error(error);
return new Response(STATUS_TEXT[Status.NotFound], {
status: Status.NotFound,
});
}
let options = {};
if (path.includes(".js")) {
options = {
headers: {
"content-type": "text/javascript",
"Cache-Control": `max-age=${maxAge}`,
},
};
}
return new Response(file.readable, options);
}
function getPathUrl(url: string, staticURL: string) {
const s = staticURL === "/" ? "" : staticURL;
const res = url.match(/^https?:\/\/[^/]+/);
if (!res) return null;
const [baseUrl] = res;
const p = `${s}/:file`;
const pattern = new URLPattern(p, baseUrl);
if (!pattern.test(url)) return null;
return url.substring(baseUrl.length);
}