-
Notifications
You must be signed in to change notification settings - Fork 68
/
Copy pathindex.ts
45 lines (39 loc) · 1.28 KB
/
index.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
import * as path from "https://deno.land/[email protected]/path/mod.ts";
import { Eta } from "https://deno.land/x/[email protected]/src/index.ts";
import { parseArgs } from "jsr:@std/cli/parse-args";
const __dirname = new URL(".", import.meta.url).pathname;
const eta = new Eta({ views: path.join(__dirname, 'public'), cache: true });
const flags = parseArgs(Deno.args, {
string: ["port"],
default: { port: "80" },
});
async function handler(request: Request) {
const url = new URL(request.url);
let filepath = decodeURIComponent(url.pathname);
if (filepath === "/") {
filepath = "/index.eta";
} else if (filepath.toLocaleLowerCase().indexOf(".") <= 0) {
filepath = `${filepath}.eta`;
}
let file;
let response;
try {
console.log(filepath);
if (filepath.indexOf(".eta") > 0) {
response = new Response(await eta.render(filepath, {}), {
headers: { "content-type": "text/html" },
});
} else {
file = await Deno.open(__dirname + "/public" + filepath, {
read: true,
});
const readableStream = file.readable;
response = new Response(readableStream);
}
} catch (e) {
console.error(e);
response = new Response("404 Not Found", { status: 404 });
}
return response;
}
Deno.serve({ port: parseInt(flags.port) }, handler);