Skip to content

Instantly share code, notes, and snippets.

@dotysan
Last active June 6, 2021 21:10
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 dotysan/da5c1d7ba6b4f4f1f2f3288c19551908 to your computer and use it in GitHub Desktop.
Save dotysan/da5c1d7ba6b4f4f1f2f3288c19551908 to your computer and use it in GitHub Desktop.
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