-
Notifications
You must be signed in to change notification settings - Fork 230
/
staticServer.ts
91 lines (82 loc) · 2.18 KB
/
staticServer.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/*
* This is an example of a server that will serve static content out of the
* $CWD/examples/static path.
*/
import {
bold,
cyan,
green,
red,
yellow,
} from "https://deno.land/std@0.118.0/fmt/colors.ts";
import { Application, HttpError, Status } from "../mod.ts";
const app = new Application();
// Error handler middleware
app.use(async (context, next) => {
try {
await next();
} catch (e) {
if (e instanceof HttpError) {
// deno-lint-ignore no-explicit-any
context.response.status = e.status as any;
if (e.expose) {
context.response.body = `<!DOCTYPE html>
<html>
<body>
<h1>${e.status} - ${e.message}</h1>
</body>
</html>`;
} else {
context.response.body = `<!DOCTYPE html>
<html>
<body>
<h1>${e.status} - ${Status[e.status]}</h1>
</body>
</html>`;
}
} else if (e instanceof Error) {
context.response.status = 500;
context.response.body = `<!DOCTYPE html>
<html>
<body>
<h1>500 - Internal Server Error</h1>
</body>
</html>`;
console.log("Unhandled Error:", red(bold(e.message)));
console.log(e.stack);
}
}
});
// Logger
app.use(async (context, next) => {
await next();
const rt = context.response.headers.get("X-Response-Time");
console.log(
`${green(context.request.method)} ${cyan(context.request.url.pathname)} - ${
bold(
String(rt),
)
}`,
);
});
// Response Time
app.use(async (context, next) => {
const start = Date.now();
await next();
const ms = Date.now() - start;
context.response.headers.set("X-Response-Time", `${ms}ms`);
});
// Send static content
app.use(async (context) => {
await context.send({
root: `${Deno.cwd()}/examples/static`,
index: "index.html",
});
});
app.addEventListener("listen", ({ hostname, port, serverType }) => {
console.log(
bold("Start listening on ") + yellow(`${hostname}:${port}`),
);
console.log(bold(" using HTTP server: " + yellow(serverType)));
});
await app.listen({ hostname: "127.0.0.1", port: 8000 });