Last active
June 6, 2021 21:10
-
-
Save dotysan/da5c1d7ba6b4f4f1f2f3288c19551908 to your computer and use it in GitHub Desktop.
the default code when you create a new 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 }) | |
) | |
); | |
}); | |
/** | |
* Many more examples available at: | |
* https://developers.cloudflare.com/workers/examples | |
* @param {Request} request | |
* @returns {Promise<Response>} | |
*/ | |
async function handleRequest(request) { | |
const { pathname } = new URL(request.url); | |
if (pathname.startsWith("/api")) { | |
return new Response(JSON.stringify({ pathname }), { | |
headers: { "Content-Type": "application/json" }, | |
}); | |
} | |
if (pathname.startsWith("/status")) { | |
const httpStatusCode = Number(pathname.split("/")[2]); | |
const nocat= new Response("That's not a valid HTTP status code."); | |
if(!Number.isInteger(httpStatusCode)) return nocat; | |
const cat= await fetch("https://http.cat/" + httpStatusCode); | |
return cat.status ===200 ? cat : nocat; | |
} | |
return fetch("https://welcome.developers.workers.dev"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment