Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
the default code when you create a new Cloudflare Worker
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