Created
May 25, 2021 03:38
-
-
Save kmonsoor/dc9f96660423c96471f8574ba018d867 to your computer and use it in GitHub Desktop.
Core worker code for url-forwarder based on Cloudflare Worker-KV
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
// This is the companion code for the linked blog | |
// https://blog.kmonsoor.com/on-edge-shortlink-server-cloudflare-kv-worker | |
// Please check the blog to get the context | |
// author : Khaled Monsoor (@kmonsoor) | |
// last updated: 25-May-2021 | |
const failsafeURL = "https://kmonsoor.com" // replace it with yours ;) | |
const defaultStatusCode = 301 // standard HTTP code for redirection, don't change | |
addEventListener("fetch", (event) => { | |
event.respondWith(handleRequest(event.request)); | |
}); | |
async function handleRequest(request) { | |
// console.log(request); | |
const requestURL = new URL(request.url); | |
if (requestURL.pathname === '/') | |
return Response.redirect(failsafeURL, defaultStatusCode); | |
const keySource = requestURL.pathname.substring(1); | |
// console.log(keySource); | |
const destinationURL = await GO_REDIRECTS.get(keySource); | |
// console.log(destinationURL); | |
if (destinationURL === null) { | |
// the message below can be updated as per your audience | |
return new Response("We couldn't find any such page", {status: 404}) | |
} | |
else return Response.redirect(destinationURL, defaultStatusCode); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment