Created
May 18, 2024 15:31
-
-
Save NotoriousPyro/f93ccd9438b8ac00309a23688f551060 to your computer and use it in GitHub Desktop.
Solana RPC Cloudflare Worker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default { | |
async fetch(request, env) { | |
const url = new URL(request.url); | |
if (url.pathname.startsWith("/api")) { | |
url.pathname = url.pathname.replace("/api", `/${env.API_KEY}`); | |
const upgradeHeader = request.headers.get('Upgrade'); | |
const newUrl = `https://api.sexonsol.com${url.pathname}`; | |
if (upgradeHeader === 'websocket') { | |
const resp = await fetch(newUrl, { | |
headers: { | |
Upgrade: 'websocket', | |
} | |
}); | |
const ws = resp.webSocket; | |
if (!ws) { | |
throw new Error("server didn't accept WebSocket"); | |
} | |
return new Response(null, { | |
status: 101, | |
webSocket: ws, | |
}); | |
} | |
const data = await fetch(newUrl, { | |
body: request.body || undefined, | |
method: request.method, | |
redirect: "manual", | |
headers: request.headers, | |
}) | |
if (data.status === 301 || data.status === 302 || data.status === 303 || data.status === 307 || data.status === 308) { | |
throw new Error("Redirects are not supported"); | |
} | |
if (data.status === 401 || data.status === 403) { | |
return new Response(null, { | |
status: data.status, | |
statusText: data.statusText, | |
}); | |
} | |
let { readable, writable } = new TransformStream(); | |
data.body.pipeTo(writable); | |
return new Response(readable, data); | |
} | |
return env.ASSETS.fetch(request); | |
}, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment