Created
April 20, 2022 13:08
-
-
Save xctan/056dac5ee010b8ff72f4179ac4697d2d to your computer and use it in GitHub Desktop.
Redirect to package page on archlinux.org
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)) | |
}) | |
/** | |
* Respond with hello worker text | |
* @param {Request} request | |
*/ | |
async function handleRequest(request) { | |
const url = new URL(request.url) | |
const path = url.pathname | |
// process favicon.ico requests | |
if (path === '/favicon.ico') { | |
return new Response(null, {status: 204}) | |
} | |
if (path.length === 0 || path.endsWith('/')) { | |
return new Response('Hello worker!') | |
} | |
const package_name = path.substring(1) | |
const response = await fetch(`https://archlinux.org/packages/search/json/?name=${package_name}`) | |
.then(response => response.json()) | |
.then(json => { | |
const pkg = json.results[0] | |
const repo = pkg.repo | |
const arch = pkg.arch | |
const package_url = `https://archlinux.org/packages/${repo}/${arch}/${package_name}/` | |
console.log(`${package_name} is available at ${package_url}`) | |
// redirect to package page | |
return new Response(null, { | |
status: 302, | |
headers: { | |
'Location': package_url | |
} | |
}) | |
}) | |
.catch(error => { | |
return new Response(error.message, { status: 500 }) | |
}) | |
return response | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment