addEventListener('fetch', event => event.respondWith(handleRequest(event)));
const BACKEND_NAME = "origin_0";
const BUCKET_NAME = "betts-gcp-gcs-fastly-tutorial";
async function handleRequest(event) {
const originalReq = event.request;
let url = new URL(originalReq.url);
let page = "";
if (url.pathname.endsWith("/")) {
page = "index.html";
}
url.pathname = "/" + BUCKET_NAME + url.pathname + page;
let newReq = new Request(url, originalReq);
newReq.headers.set("Host", "storage.googleapis.com");
let resp = await fetch(newReq, {
backend: BACKEND_NAME,
});
if (resp.status == 404 && !url.pathname.endsWith("/index.html")) {
url = new URL(originalReq.url);
let directory_path = url.pathname + "/";
url.pathname = "/" + BUCKET_NAME + url.pathname + "/index.html";
newReq = new Request(url, originalReq);
newReq.headers.set("Host", "storage.googleapis.com");
resp = await fetch(newReq, {
backend: BACKEND_NAME,
});
if (resp.status == 200) {
let headers = new Headers({"location": directory_path});
resp = new Response('', {status: 301, headers});
}
}
return resp;
};