-
Notifications
You must be signed in to change notification settings - Fork 230
/
closeServer.ts
75 lines (63 loc) · 1.82 KB
/
closeServer.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
/*
* This is an example of a server that closes when hitting the /close route.
*/
// Importing some console colors
import {
bold,
cyan,
green,
yellow,
} from "https://deno.land/std@0.95.0/fmt/colors.ts";
import { Application, Context, Router, Status } from "../mod.ts";
function notFound(context: Context) {
context.response.status = Status.NotFound;
context.response.body =
`<html><body><h1>404 - Not Found</h1><p>Path <code>${context.request.url}</code> not found.`;
}
const controller = new AbortController();
const router = new Router();
router
.get("/", (context) => {
context.response.body = "Hello world!";
})
.get("/close", (context) => {
context.response.body = "Bye!";
// This will cause the application to stop listening and stop processing
// requests
controller.abort();
});
const app = new Application();
// 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`);
});
// Use the router
app.use(router.routes());
app.use(router.allowedMethods());
// A basic 404 page
app.use(notFound);
app.addEventListener("listen", ({ hostname, port, serverType }) => {
console.log(
bold("Start listening on ") + yellow(`${hostname}:${port}`),
);
console.log(bold(" using HTTP server: " + yellow(serverType)));
});
// Utilise the signal from the controller
const { signal } = controller;
await app.listen({ hostname: "127.0.0.1", port: 8000, signal });
console.log(bold("Finished."));