-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
49 lines (43 loc) · 1.69 KB
/
Copy pathserver.ts
File metadata and controls
49 lines (43 loc) · 1.69 KB
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
import { connectProtocolFromRequest } from "captun";
import { acceptFetcherCapabilityFromDenoSocket } from "captun/deno";
let egressTunnel: ReturnType<typeof acceptFetcherCapabilityFromDenoSocket> | undefined;
const egressFetch: typeof fetch = async (input, init) => {
if (egressTunnel) return egressTunnel.fetch(new Request(input, init));
return fetch(input, init);
};
const server = Deno.serve(
{ hostname: "127.0.0.1", port: Number(Deno.env.get("PORT")) },
async (request) => {
const url = new URL(request.url);
if (url.pathname === "/weather") {
const city = url.searchParams.get("city") || "";
const response = await egressFetch(`https://wttr.in/${city}?format=j1`);
const weather = (await response.json()) as {
current_condition: [{ temp_C: string }];
};
return new Response(
`The temperature in ${city} is ${weather.current_condition[0].temp_C} celsius`,
);
}
if (url.pathname === "/__intercept-egress-traffic") {
const { socket, response } = Deno.upgradeWebSocket(request, {
protocol: connectProtocolFromRequest(request),
});
socket.addEventListener("open", () => {
const tunnel = acceptFetcherCapabilityFromDenoSocket(socket, {
onDisconnect: () => {
if (egressTunnel === tunnel) egressTunnel = undefined;
},
});
egressTunnel?.[Symbol.dispose]();
egressTunnel = tunnel;
queueMicrotask(() => void tunnel.ready({ url: new URL(request.url).origin }));
});
return response;
}
return new Response("Not found\n", { status: 404 });
},
);
Deno.addSignalListener("SIGINT", () => {
server.shutdown().finally(() => Deno.exit(0));
});