Skip to content

Instantly share code, notes, and snippets.

@abersheeran
Last active January 4, 2024 03:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abersheeran/8cdc9089781fba691a765d1444aa5512 to your computer and use it in GitHub Desktop.
Save abersheeran/8cdc9089781fba691a765d1444aa5512 to your computer and use it in GitHub Desktop.
A pypi mirror cloudflare worker
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