-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.ts
37 lines (32 loc) · 1.24 KB
/
index.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
const file = Bun.file('/etc/hosts');
const text = await file.text();
const lines = text.split('\n');
const regex = /^127\.0\.0\.1 (?<name>\w+)\.localhost \# (?<port>\d+)$/;
const matches = lines.map(line => line.match(regex)).filter(Boolean);
const entries = matches.map(match => [match.groups.name, +match.groups.port]);
const map = Object.fromEntries(entries);
console.log(
Bun.serve({
port: 80,
async fetch(request) {
const hostname = new URL(request.url).hostname;
if (!hostname.endsWith('.localhost')) {
return new Response('Not Found - not .localhost', { status: 404 });
}
const name = hostname.slice(0, -'.localhost'.length);
if (!map[name]) {
return new Response('Not Found - not in /etc/hosts map', { status: 404 });
}
const url = new URL(request.url);
const host = url.host;
url.hostname = 'localhost';
url.port = map[name].toString();
const proxyRequest = new Request(url, request);
proxyRequest.headers.set("Host", host);
return await fetch(proxyRequest, { redirect: "manual" });
},
}).url.href
);
// Tell TypeScript this file can use TLA
// Note that `module` and `target` in `tsconfig.json` nor `type` in `package.json` helped
export { };