-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstatic.ts
35 lines (32 loc) · 1003 Bytes
/
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
import { contentType } from "@std/media-types/content-type";
import { extname } from "@std/path/extname";
export interface StaticFileOptions {
status?: number;
cacheControl?: string;
}
export async function staticFile(
path: string,
options?: StaticFileOptions,
): Promise<Response> {
const contentTypeValue = contentType(extname(path));
const file = await Deno.open(path);
const res = new Response(file.readable, { status: options?.status });
if (contentTypeValue) {
res.headers.append("content-type", contentTypeValue);
}
res.headers.append("cache-control", options?.cacheControl ?? "no-cache");
return res;
}
export function decodeURLPathComponents(pathname: string): string[] | null {
const segments = pathname.split("/").filter(Boolean);
let components: string[];
try {
components = segments.map(decodeURIComponent);
} catch {
return null;
}
if (components.some((component) => /[/\\]/.test(component))) {
return null;
}
return components;
}