-
Notifications
You must be signed in to change notification settings - Fork 2
/
StaticHandler.ts
50 lines (45 loc) · 1.47 KB
/
StaticHandler.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
import { ServerRequest } from "https://deno.land/std/http/server.ts";
import { parse, join, sep } from "https://deno.land/std/path/mod.ts";
import { contentType } from "https://deno.land/x/media_types/mod.ts";
export class StaticHandler {
private localFolderPath: string = "";
public staticUrlPrefix: string = "";
constructor(localFolderPath: string, urlPrefix: string = "") {
this.localFolderPath = localFolderPath;
this.staticUrlPrefix = urlPrefix;
if (!urlPrefix) {
this.staticUrlPrefix = parse(localFolderPath).base;
}
if (this.staticUrlPrefix[0] !== "/") {
this.staticUrlPrefix = `/${this.staticUrlPrefix}`;
}
}
public async process(req: ServerRequest) {
let responseObject: any = { status: 200 };
try {
let localFile = join(
this.localFolderPath,
req.url.replace(this.staticUrlPrefix, "").replace("/", sep)
);
if (localFile === this.localFolderPath) {
localFile += "/index.html";
}
let data = await Deno.readFile(localFile);
if (!data) {
throw new Deno.errors.NotFound();
}
responseObject.body = data;
responseObject.headers = new Headers({
"content-type":
contentType(localFile.split(".").reverse()[0]) ||
"application/octet-stream",
});
} catch (error) {
responseObject.status = 401;
if (error.name === "NotFound") {
responseObject.status = 404;
}
}
req.respond(responseObject);
}
}