From 433af168530fabc5814cc7e515e5b76c6d6ae15c Mon Sep 17 00:00:00 2001 From: Dan Date: Thu, 21 Dec 2017 22:52:52 -0800 Subject: [PATCH] Redirect to trailing slash version of page. --- src/fetcher.js | 28 +++++++++++++++++++++++----- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/src/fetcher.js b/src/fetcher.js index 492e839..1df1e61 100644 --- a/src/fetcher.js +++ b/src/fetcher.js @@ -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('404 Not Found

404 Not Found


Intergalactic
'), {'Content-Type': 'text/html; charset=utf-8'} ) + }).catch((error) => { + console.log(error) }) ) })