-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.ts
55 lines (48 loc) · 1.84 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
// import * as base64 from "@std/encoding/base64";
const corsDisableHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "*",
};
const handleProxyHttpRequest = async (_req: Request) => {
if (_req.method === "OPTIONS") {
return new Response("Hi!", { headers: corsDisableHeaders });
}
// console.log("request:", _req);
// console.log("request.url:", _req.url);
const originUrlObj = new URL(_req.url);
if (originUrlObj.pathname.length === 1) {
return new Response(
"Welcome to the Edge Http Proxy! Put any URL you want to proxy in path"
);
}
let targetHeaders = _req.headers;
const targetHeadersSerializedEncoded =
originUrlObj.searchParams.get("__headers");
if (targetHeadersSerializedEncoded) {
const targetHeadersSerialized = decodeURIComponent(
targetHeadersSerializedEncoded
);
// const targetHeadersSerializedArr = base64.decodeBase64(
// targetHeadersSerializedEncoded
// );
// const targetHeadersSerialized = targetHeadersSerializedArr.toString();
targetHeaders = new Headers(JSON.parse(targetHeadersSerialized));
// console.log("targetHeaders", targetHeaders);
}
const targetUrl = originUrlObj.pathname.slice(1) + originUrlObj.search;
// console.log("target url:", targetUrl);
const responseProxied = await fetch(targetUrl, {
..._req,
headers: targetHeaders,
});
const proxiedCorsHeaders = new Headers(responseProxied.headers);
for (const corsDisableHeader of Object.entries(corsDisableHeaders)) {
// replace proxy cors header instead of concat
proxiedCorsHeaders.set(...corsDisableHeader);
}
return new Response(responseProxied.body, {
headers: proxiedCorsHeaders,
});
};
Deno.serve({ hostname: "0.0.0.0", port: 8000 }, handleProxyHttpRequest);