forked from ekzhang/rustpad
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
67 lines (60 loc) · 2.25 KB
/
server.ts
File metadata and controls
67 lines (60 loc) · 2.25 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
import { serve } from "bun";
import index from "./index.html";
const PROXY_TARGET = "http://localhost:3030";
const server = serve({
routes: {
"/": index,
"/api/*": (req) => {
const url = new URL(req.url);
// Check for WebSocket upgrade
if (req.headers.get('upgrade')?.toLowerCase() === 'websocket') {
// Pass the URL and other request info to the WebSocket handler
server.upgrade(req, {
data: {
url: url,
backend: undefined,
}
});
return undefined; // Must return undefined after successful upgrade
}
const backendUrl = new URL(url.pathname, PROXY_TARGET);
return fetch(backendUrl, {
method: req.method,
headers: req.headers,
body: req.body,
});
},
},
websocket: {
open(ws) {
if (ws.data.backend) {
console.warn("WebSocket already has a backend connection");
return;
}
// Access the URL from ws.data
console.log("WebSocket opened for:", ws.data.url.toString());
// Now you can use it to construct the backend WebSocket URL
const path = ws.data.url.pathname;
const backendUrl = new URL(path, PROXY_TARGET);
const backend = new WebSocket(backendUrl);
ws.data.backend = backend;
backend.onopen = () => console.log('Backend WS connected');
backend.onmessage = (event) => ws.send(event.data);
backend.onclose = () => ws.close();
backend.onerror = (err) => {
console.error('Backend WS error:', err);
ws.close();
};
},
message(ws, message) {
console.log("WebSocket message received:", message);
ws.data.backend?.send(message);
},
close(ws) {
console.log("WebSocket closed");
ws.data.backend?.close();
},
} as Bun.WebSocketHandler<{ url: URL; backend: WebSocket | undefined }>,
development: true,
});
console.log(`Listening on ${server.url}`);