Skip to content

Instantly share code, notes, and snippets.

@jthomas
Created July 24, 2019 14:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jthomas/3c6c1db53e6f8ae7e70e2238b8c3374b to your computer and use it in GitHub Desktop.
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.
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