Created
April 13, 2024 03:04
-
-
Save wkgcass/5636c467142daea11d398dc4c1f9e715 to your computer and use it in GitHub Desktop.
Use Cloudflare Workers to proxy git requests to Github
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
addEventListener('fetch', event => { | |
event.respondWith(handleRequest(event.request)) | |
}) | |
async function handleRequest(request) { | |
let url = request.url | |
if (url.indexOf("://") !== -1) { | |
url = url.substring(url.indexOf("://") + "://".length) | |
} | |
if (url.indexOf("/") !== -1) { | |
url = url.substring(url.indexOf("/")) | |
} | |
const targetURL = new URL("https://github.com" + url) | |
console.log("targetURL = " + targetURL + ", method = " + request.method) | |
const newHeaders = new Headers(request.headers) | |
newHeaders.set('host', targetURL.host) | |
let headersDebugStr = 'newHeaders =' | |
for (const h of newHeaders.entries()) { | |
const key = h[0] | |
if (key.startsWith("cf-") || key == 'x-forwarded-proto' || key == 'x-real-ip') { | |
newHeaders.delete(key) | |
continue | |
} | |
headersDebugStr += ' | ' + h[0] + ':' + h[1] + ' ' | |
} | |
console.log(headersDebugStr) | |
const newRequest = new Request(targetURL, { | |
method: request.method, | |
headers: newHeaders, | |
body: request.body | |
}) | |
const response = await fetch(newRequest) | |
headersDebugStr = 'response.headers =' | |
for (const h of response.headers.entries()) { | |
headersDebugStr += ' | ' + h[0] + ':' + h[1] + ' ' | |
} | |
console.log(headersDebugStr) | |
// Create a new response object based on the original response | |
const newResponse = new Response(response.body, { | |
status: response.status, | |
statusText: response.statusText, | |
headers: response.headers, | |
}) | |
console.log("response.status = " + response.status) | |
return newResponse | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment