Last active
January 4, 2024 03:16
-
-
Save abersheeran/8cdc9089781fba691a765d1444aa5512 to your computer and use it in GitHub Desktop.
A pypi mirror 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
addEventListener("fetch", (event) => { | |
event.respondWith( | |
handleRequest(event.request).catch( | |
(err) => new Response(err.stack, { status: 500 }) | |
) | |
); | |
}); | |
async function handleRequest(request) { | |
const { host, pathname } = new URL(request.url) | |
if (pathname.startsWith("/simple")) { | |
const resp = await fetch(`https://pypi.org${pathname}`) | |
const text = await resp.text() | |
const replace_re = /:\/\/files.pythonhosted.org\//g | |
const replace_target = `://${host}/` | |
return new Response( | |
text.replace(replace_re, replace_target), | |
{ | |
headers: resp.headers, | |
} | |
) | |
} | |
if (pathname.startsWith("/packages")) { | |
return await fetch(`https://files.pythonhosted.org${pathname}`) | |
} | |
if (pathname.startsWith("/pypi")) { | |
return await fetch(`https://pypi.org${pathname}`) | |
} | |
return new Response( | |
`This is a <a href="https://pypi.org/simple/">PyPi</a> mirror that created by <a href="https://github.com/abersheeran">Aber</a>.`, | |
{ | |
headers: { "Content-Type": "text/html" }, | |
status: 404, | |
} | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment