Skip to content

Instantly share code, notes, and snippets.

@PierBover
Created September 14, 2021 23:37
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PierBover/226b4dac0ca3ed4c19372288a24631d4 to your computer and use it in GitHub Desktop.
Save PierBover/226b4dac0ca3ed4c19372288a24631d4 to your computer and use it in GitHub Desktop.
Cloudflare Worker audio streaming from Backblaze B2
const cache = caches.default;
addEventListener("fetch", (event) => {
try {
const request = event.request
return event.respondWith(handleRequest(event))
} catch (e) {
return event.respondWith(new Response("Error thrown " + e.message))
}
});
async function handleRequest (event) {
const request = event.request;
const cacheUrl = new URL(request.url);
// Construct the cache key from the origin URL and the request
// The Range header will be included in the request
const originUrl = 'https://f000.backblazeb2.com/file/bucket-name' + cacheUrl.pathname;
const cacheKeyRequest = new Request(originUrl, request);
// Return cached range bytes
const cachedResponse = await cache.match(cacheKeyRequest);
if (cachedResponse) return cachedResponse;
// If the file is not cached fetch the file from origin
const originResponse = await fetch(cacheKeyRequest);
// Create a new response so we can strip B2 headers
const response = new Response(originResponse.body);
response.headers.append("Cache-Control", "s-maxage=500");
response.headers.append("content-type", "audio/mpeg");
// Save the full file to the cache once the response has been sent to the client
event.waitUntil(cache.put(cacheKeyRequest, response.clone()));
return response;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment