-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserve.ts
More file actions
64 lines (48 loc) · 1.56 KB
/
Copy pathserve.ts
File metadata and controls
64 lines (48 loc) · 1.56 KB
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
import {
serveVisitorCount,
serveVisitorStatus,
trackHtmlVisit,
} from "./serve/counter.ts";
import { filePath, isDirectory, serveFile } from "./serve/files.ts";
const root = `${Deno.cwd()}/_site`;
async function handler(request: Request) {
const requestUrl = new URL(request.url);
const hostname = request.headers.get("host")?.split(":")[0].toLowerCase();
if (requestUrl.pathname === "/api/visitor-count") {
return serveVisitorCount(requestUrl);
}
if (requestUrl.pathname === "/api/status") {
return serveVisitorStatus();
}
if (hostname === "www.rix1.dev") {
requestUrl.protocol = "https:";
requestUrl.hostname = "rix1.dev";
return Response.redirect(requestUrl, 308);
}
const path = filePath(root, requestUrl.pathname);
if (!path) {
return serveFile(`${root}/404.html`, 404);
}
if (!requestUrl.pathname.endsWith("/") && await isDirectory(path)) {
requestUrl.pathname = `${requestUrl.pathname}/`;
return Response.redirect(requestUrl, 308);
}
const response = await serveFile(path);
if (response.status === 404) {
return serveFile(`${root}/404.html`, 404);
}
if (request.method === "GET" && path.endsWith(".html")) {
const { cookie } = await trackHtmlVisit(request, requestUrl);
if (cookie) {
response.headers.set("set-cookie", cookie);
}
response.headers.set("cache-control", "no-store");
}
return response;
}
if (Deno.env.get("DENO_DEPLOYMENT_ID")) {
Deno.serve(handler);
} else {
Deno.serve({ port: 8000 }, handler);
console.log("Listening on http://localhost:8000");
}