-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrouter.ts
More file actions
76 lines (65 loc) · 2.11 KB
/
Copy pathrouter.ts
File metadata and controls
76 lines (65 loc) · 2.11 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
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
const server = Bun.serve({
port: 3004,
hostname: "0.0.0.0",
async fetch(req) {
// First check for header-based routing
const appName = req.headers.get('fly-app-name');
const machineId = req.headers.get('fly-machine-id');
if (appName) {
// Header-based routing
let replayHeader = `app=${appName}`;
if (machineId) {
replayHeader += `;instance=${machineId}`;
}
return new Response(
`Replaying request to: ${replayHeader} (via headers)`,
{
status: 200,
headers: {
'Content-Type': 'text/plain',
'fly-replay': replayHeader
}
}
);
}
// Fall back to hostname-based routing
const url = new URL(req.url);
const hostname = url.hostname;
// Parse hostname pattern: <machine-id>.<app-name>.example.com or <app-name>.example.com
const parts = hostname.split('.');
if (parts.length < 3) {
return new Response('Invalid hostname format. Use either <machine-id>.<app-name>.example.com or <app-name>.example.com, or set fly-app-name and optionally fly-machine-id headers', {
status: 400
});
}
// Remove .example.com from the end
const domainParts = parts.slice(0, -2);
let hostMachineId: string | undefined;
let hostAppName: string;
if (domainParts.length === 2) {
// Format: <machine-id>.<app-name>
[hostMachineId, hostAppName] = domainParts;
} else if (domainParts.length === 1) {
// Format: <app-name>
hostAppName = domainParts[0];
} else {
return new Response('Invalid hostname format', { status: 400 });
}
// Construct fly-replay header
let replayHeader = `app=${hostAppName}`;
if (hostMachineId) {
replayHeader += `;instance=${hostMachineId}`;
}
return new Response(
`Replaying request to: ${replayHeader} (via hostname)`,
{
status: 200,
headers: {
'Content-Type': 'text/plain',
'fly-replay': replayHeader
}
}
);
}
});
console.log(`🚀 Router server running at http://0.0.0.0:${server.port}`);