Redirect to trailing slash version of page.

This commit is contained in:
Dan 2017-12-21 22:52:52 -08:00
parent 5624a03168
commit 433af16853
1 changed files with 23 additions and 5 deletions

View File

@ -72,16 +72,34 @@ self.addEventListener('fetch', (event) => {
ipfs_initialized.then(() => {
const url = new URL(event.request.url)
const multihash = url.pathname
return node.files.cat(multihash)
}).then((contents_buffer) => {
return response(200, 'OK', contents_buffer)
}).catch((error) => {
console.log(error)
return node.files.get(multihash)
}).then((files) => {
// If there's just one result, return it.
if (files.length == 1 && files[0].content) {
return response(200, 'OK', files[0].content)
}
// If there are multiple results (and so this appears to be a directory), but this URL
// doesn't have a trailing slash, redirect. This ensures relative paths work correctly
// for any resources pulled in on the page.
if (files.length > 1 && event.request.url.slice(-1) != '/') {
return response(302, 'Found', '', {'Location': event.request.url + '/'})
}
// If there are multiple results, look for an index.html page to return.
for (let file of files) {
if (file.path.endsWith('/index.html')) {
return response(200, 'OK', file.content)
}
}
return response(
404, 'Not Found',
Buffer.from('<html><head><title>404 Not Found</title></head><body bgcolor="white"><center><h1>404 Not Found</h1></center><hr><center>Intergalactic</center></body></html>'),
{'Content-Type': 'text/html; charset=utf-8'}
)
}).catch((error) => {
console.log(error)
})
)
})