Created
December 6, 2021 19:53
-
-
Save mstange/ed6f7e494b763abc755f3d6e753924ee to your computer and use it in GitHub Desktop.
Cloudflare worker which serves raw source code from googlesource.com
This file contains hidden or 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
/** | |
* This worker makes sourcecode from googlesource.com accessible as | |
* plain text, with permissive CORS headers. | |
* This is a workaround for https://github.com/google/gitiles/issues/7 : | |
* googlesource.com currently only serves base64-encoded sources, and is | |
* not accessible by cross-site requests. | |
* | |
* Request URL format: /<subdomain>/<path> | |
* This gets the code from https://<subdomain>.googlesource.com/<path>?format=TEXT | |
* and base64-decodes it. | |
*/ | |
// All responses need to have permissive CORS headers. | |
function responseWithStatus(status, responseText) { | |
return new Response( | |
responseText, | |
{ | |
status, | |
headers: { | |
"Content-Type": "text/plain; charset=utf-8", | |
"Access-Control-Allow-Origin": "*", | |
"X-Content-Type-Options": "nosniff", | |
}, | |
} | |
); | |
} | |
const routeRegExp = new RegExp("^/(?<subdomain>.*?)/(?<path>.*)$"); | |
async function handleRequest(request) { | |
// GET /<subdomain>/<path> | |
const pathname = new URL(request.url).pathname; | |
const match = routeRegExp.exec(pathname); | |
if (match === null) { | |
return responseWithStatus( | |
404, | |
"Format: /<subdomain>/<path>, fetches https://<subdomain>.googlesource.com/<path>?format=TEXT" | |
); | |
} | |
const { subdomain, path } = match.groups; | |
const url = `https://${subdomain}.googlesource.com/${path}?format=TEXT`; | |
const response = await fetch(url); | |
if (response.status !== 200) { | |
return responseWithStatus( | |
response.status, | |
`${url} returned status ${response.status} (${response.statusText})` | |
); | |
} | |
try { | |
// Get the base64-encoded text and decode it. | |
const encodedText = await response.text(); | |
const text = atob(encodedText); | |
return responseWithStatus(200, text); | |
} catch (e) { | |
throw new Error(`Error parsing response from ${url}: ${e}`); | |
} | |
} | |
addEventListener("fetch", (event) => { | |
event.respondWith( | |
handleRequest(event.request).catch( | |
(err) => responseWithStatus(500, `${err.name}: ${err.message}\n${err.stack}`) | |
) | |
); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment