/
proxyServer.ts
91 lines (81 loc) · 2.31 KB
/
proxyServer.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 proxy server.
*/
import { bold, cyan, green, red, yellow } from "jsr:@std/fmt@0.223/colors";
import { Application, HttpError, proxy, 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`);
});
// Redirects requests to `/` to `/oak/` which is the appropriate path to
// proxy.
app.use((ctx, next) => {
if (ctx.request.url.pathname === "/") {
ctx.response.redirect("/oak/");
} else {
return next();
}
});
// Proxy requests
app.use(proxy("https://oakserver.github.io/"));
// Log when we start listening for requests
app.addEventListener("listen", ({ hostname, port, serverType }) => {
console.log(
`${bold("Start listening on ")}${yellow(`${hostname}:${port}`)}`,
);
console.log(bold(` using HTTP server: ${yellow(serverType)}`));
});
// Start listening to requests
await app.listen({ hostname: "127.0.0.1", port: 8000 });