Skip to content

Commit 09e75a6

Browse files
committed
Commit
1 parent 7dc673b commit 09e75a6

2 files changed

Lines changed: 71 additions & 0 deletions

File tree

worker.js

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
export default {
2+
async fetch(request, env, ctx) {
3+
// 1. Define your target (Render)
4+
const TARGET_URL = "https://random-rants-plus.onrender.com";
5+
6+
// 2. Parse the incoming request URL
7+
const url = new URL(request.url);
8+
const target = new URL(TARGET_URL);
9+
10+
// 3. Copy the path and query params (e.g., /socket.io/?EIO=4...)
11+
url.hostname = target.hostname;
12+
url.protocol = target.protocol;
13+
url.port = target.port;
14+
15+
// 4. Handle WebSocket Upgrades specifically
16+
const upgradeHeader = request.headers.get('Upgrade');
17+
if (upgradeHeader === 'websocket') {
18+
return await handleWebSocket(request, url);
19+
}
20+
21+
// 5. Handle Standard HTTP Requests (GET, POST, PUT, etc.)
22+
// We create a new request with the same body and headers
23+
const newRequest = new Request(url, {
24+
method: request.method,
25+
headers: request.headers,
26+
body: request.body,
27+
redirect: 'follow'
28+
});
29+
30+
// 6. Send to Render and return the response
31+
return fetch(newRequest);
32+
}
33+
};
34+
35+
// Helper function to handle the WebSocket handshake
36+
async function handleWebSocket(request, url) {
37+
// Create a new request specifically for the WebSocket handshake
38+
const wsRequest = new Request(url, {
39+
method: request.method,
40+
headers: request.headers,
41+
redirect: 'follow'
42+
});
43+
44+
// Fetch the remote WebSocket
45+
const response = await fetch(wsRequest);
46+
47+
// If the remote server accepted the upgrade (Status 101), return it
48+
if (response.status === 101) {
49+
// Cloudflare Workers automatically handles the piping of the WebSocket
50+
return response;
51+
}
52+
53+
// If it failed, return the error
54+
return response;
55+
}

wrangler.jsonc

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
{
2+
"name": "random-rants-proxy",
3+
"main": "worker.js",
4+
"compatibility_date": "2024-02-16",
5+
6+
// This enables standard Node.js APIs if you need them later
7+
"compatibility_flags": [ "nodejs_compat" ],
8+
9+
// IMPORTANT: Do NOT include an "assets" or "site" section here.
10+
// If you include "assets", Cloudflare will try to serve static files
11+
// instead of running your proxy script.
12+
13+
"observability": {
14+
"enabled": true
15+
}
16+
}

0 commit comments

Comments
 (0)