Skip to content

Instantly share code, notes, and snippets.

@richie5um
Created May 24, 2022 21:28
Show Gist options
  • Save richie5um/05a2573336dc6644f653a5e087e7c48b to your computer and use it in GitHub Desktop.
Save richie5um/05a2573336dc6644f653a5e087e7c48b to your computer and use it in GitHub Desktop.
import { getAssetFromKV, mapRequestToAsset } from "@cloudflare/kv-asset-handler";
addEventListener("fetch", (event) => {
event.respondWith(handleEvent(event));
});
async function handleEvent(event) {
try {
if (event.request.url.endsWith('.gz')) {
let resp = await getAssetFromKV(event);
// // Make a new response with the same body but using manual encoding.
resp = new Response(resp.body, {
status: resp.status,
headers: resp.headers,
encodeBody: "manual"
});
if (event.request.url.endsWith('.wasm.gz')) {
resp.headers.set("Content-Type", "application/wasm");
} else if (event.request.url.endsWith('.data.gz')) {
resp.headers.set("Content-Type", "application/octet-stream");
} else if (event.request.url.endsWith('.js.gz')) {
resp.headers.set("Content-Type", "application/javascript");
}
resp.headers.set("Content-Encoding", "gzip");
return resp;
}
// Add logic to decide whether to serve an asset or run your original Worker code
return await getAssetFromKV(event);
} catch (e) {
let pathname = new URL(event.request.url).pathname;
return new Response(`"${pathname}" not found`, {
status: 404,
statusText: "not found",
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment