-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathproxy.ts
89 lines (71 loc) · 2.07 KB
/
proxy.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
export default class {
prefix: string;
wsPrefix: string;
debug: boolean;
constructor(prefix: string, wsPrefix: string, debug?: boolean) {
this.prefix = prefix;
this.wsPrefix = wsPrefix;
this.debug = debug ?? false;
}
route(path: string): boolean {
return path === this.prefix;
}
routeWs(path: string): boolean {
return path.startsWith(this.wsPrefix);
}
async handle(req: Request): Promise<Response> {
const url: string = req.headers.get("x-url") || "";
// deno-lint-ignore ban-types
const headers: Object = JSON.parse(req.headers.get("x-headers") || "");
if (this.debug) console.log(`Handling ${url}`);
try {
const opts: {
method: string;
// deno-lint-ignore no-explicit-any
headers: any;
body?: string;
} = {
method: req.method,
headers: headers,
};
if (opts.method === "POST") {
opts.body = await req.text();
console.log(`${req.method} ${url}`);
}
const proxyResp: Response = await fetch(url, opts);
const respHeaders = Object.fromEntries(proxyResp.headers.entries());
// Don't cache
delete respHeaders["age"];
delete respHeaders["cache-control"];
delete respHeaders["expires"];
return new Response(await proxyResp.body, {
status: proxyResp.status,
headers: {
"cache-control": "no-cache",
...respHeaders,
},
});
} catch (err) {
return new Response(err.message, { status: 500 });
}
}
handleWs(req: Request): Response {
let resp: Response, sock: WebSocket;
const proto: string = req.headers.get("sec-websocket-protocol") || "";
try {
({ response: resp, socket: sock } = Deno.upgradeWebSocket(req, {
protocol: proto,
}));
} catch {
return new Response("Not a WS connection");
}
const url: string = new URL(req.url).searchParams.get("url") || "";
if (this.debug) console.log(`Handling WS ${url}`);
const proxySock = new WebSocket(url, proto);
sock.onmessage = e => proxySock.send(e.data);
proxySock.onmessage = e => sock.send(e.data);
sock.onclose = () => proxySock.close();
proxySock.onclose = () => sock.close();
return resp;
}
}