-
Notifications
You must be signed in to change notification settings - Fork 33
/
main.ts
84 lines (73 loc) · 2.16 KB
/
main.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
import { serve } from "https://deno.land/[email protected]/http/server.ts";
import { CSS, render } from "https://deno.land/x/[email protected]/mod.ts";
function addCorsIfNeeded(response: Response) {
const headers = new Headers(response.headers);
if (!headers.has("access-control-allow-origin")) {
headers.set("access-control-allow-origin", "*");
}
return headers;
}
function isUrl(url: string) {
if (!url.startsWith("http://") && !url.startsWith("https://")) {
return false;
}
try {
new URL(url);
return true;
} catch {
return false;
}
}
async function handleRequest(request: Request) {
const { pathname, search } = new URL(request.url);
const url = pathname.substring(1) + search;
if (isUrl(url)) {
console.log("proxy to %s", url);
const corsHeaders = addCorsIfNeeded(new Response());
if (request.method.toUpperCase() === "OPTIONS") {
return new Response(null, { headers: corsHeaders });
}
const response = await fetch(url, request);
const headers = addCorsIfNeeded(response);
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers,
});
}
const readme = await Deno.readTextFile("./README.md");
const body = render(readme);
const html = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CORS Proxy</title>
<style>
body {
margin: 0;
background-color: var(--color-canvas-default);
color: var(--color-fg-default);
}
main {
max-width: 800px;
margin: 0 auto;
padding: 2rem 1rem;
}
${CSS}
</style>
</head>
<body data-color-mode="auto" data-light-theme="light" data-dark-theme="dark">
<main class="markdown-body">
${body}
</main>
</body>
</html>`;
return new Response(html, {
headers: {
"content-type": "text/html;charset=utf-8",
},
});
}
const port = Deno.env.get("PORT") ?? "8000";
serve(handleRequest, { port: Number(port) });