export default {
async fetch(request, env, ctx): Promise<Response> {
const url = new URL(request.url)
const key = url.pathname.slice(1)
if (request.method !== "GET") {
return new Response("Method not allowed", { status: 405 })
}
if (!key) {
return new Response("No key provided", { status: 400 })
}
const cache = caches.default
const cacheKey = new Request(url.toString(), request)
const cachedResponse = await cache.match(cacheKey)
if (cachedResponse) {
return cachedResponse
}
if (key.startsWith("uploads")) {
return new Response("Uploaded files are not available for download", { status: 404 })
}
const object = await env.BUCKET.get(key)
if (!object) {
return new Response("Not found", { status: 404 })
}
const headers = new Headers()
object.writeHttpMetadata(headers)
headers.set("etag", object.httpEtag)
headers.set("Content-Type", object.httpMetadata?.contentType ?? "application/octet-stream")
headers.set("Content-Length", object.size.toString())
headers.set("Cache-Control", "public, max-age=3600")
headers.set("Vary", "Accept-Encoding")
const response = new Response(object.body, { headers })
ctx.waitUntil(cache.put(cacheKey, response.clone()))
return response
},
} satisfies ExportedHandler<Env>
export default {
async fetch(request, env, ctx): Promise<Response> {
const url = new URL(request.url)
const key = url.pathname.slice(1)
if (request.method !== "GET") {
return new Response("Method not allowed", { status: 405 })
}
if (!key) {
return new Response("No key provided", { status: 400 })
}
const cache = caches.default
const cacheKey = new Request(url.toString(), request)
const cachedResponse = await cache.match(cacheKey)
if (cachedResponse) {
return cachedResponse
}
if (key.startsWith("uploads")) {
return new Response("Uploaded files are not available for download", { status: 404 })
}
const object = await env.BUCKET.get(key)
if (!object) {
return new Response("Not found", { status: 404 })
}
const headers = new Headers()
object.writeHttpMetadata(headers)
headers.set("etag", object.httpEtag)
headers.set("Content-Type", object.httpMetadata?.contentType ?? "application/octet-stream")
headers.set("Content-Length", object.size.toString())
headers.set("Cache-Control", "public, max-age=3600")
headers.set("Vary", "Accept-Encoding")
const response = new Response(object.body, { headers })
ctx.waitUntil(cache.put(cacheKey, response.clone()))
return response
},
} satisfies ExportedHandler<Env>