Skip to content

Instantly share code, notes, and snippets.

@KhaledSMQ
Forked from jthomas/worker.js
Created July 24, 2019 17:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KhaledSMQ/b1b5507f4e3f26ed2e4747484fceb8e7 to your computer and use it in GitHub Desktop.
Save KhaledSMQ/b1b5507f4e3f26ed2e4747484fceb8e7 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