Created
July 24, 2019 14:51
-
-
Save jthomas/3c6c1db53e6f8ae7e70e2238b8c3374b to your computer and use it in GitHub Desktop.
Using IBM Cloud Edge Functions (Cloudflare Workers) to add support for Index and Error documents for Cloud Object Storage static hosting.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const INDEX_DOCUMENT = 'index.html' | |
const ERROR_DOCUMENT = '404.html' | |
addEventListener('fetch', event => { | |
event.respondWith(handleRequest(event.request)) | |
}) | |
/** | |
* @param {Request} request | |
*/ | |
async function handleRequest(request) { | |
const url = new URL(request.url) | |
if (url.pathname.endsWith('/')) { | |
url.pathname = `${url.pathname}${INDEX_DOCUMENT}` | |
request = new Request(url, request) | |
} | |
let response = await fetch(request) | |
if (response.status === 404) { | |
url.pathname = ERROR_DOCUMENT | |
request = new Request(url, request) | |
response = await fetch(request) | |
response = new Response(response.body, { | |
status: 404, | |
statusText: 'Not Found', | |
headers: response.headers | |
}) | |
} | |
return response | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment