Skip to content
This repository has been archived by the owner on Sep 12, 2019. It is now read-only.

Handle alternative paths the same way as when deployed #70

Merged
merged 1 commit into from
Apr 4, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"bugs": "https://github.com/netlify/netlify-dev-plugin/issues",
"dependencies": {
"@netlify/cli-utils": "^1.0.1",
"@netlify/rules-proxy": "^0.1.0",
"@netlify/rules-proxy": "^0.1.1",
"@netlify/zip-it-and-ship-it": "^0.1.3",
"@oclif/command": "^1",
"@oclif/config": "^1",
Expand Down
55 changes: 55 additions & 0 deletions src/commands/dev/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,61 @@ function addonUrl(addonUrls, req) {
return addonUrl ? `${addonUrl}${m[2]}` : null;
}

// Used as an optimization to avoid dual lookups for missing assets
const assetExtensionRegExp = /\.(html?|png|jpg|js|css|svg|gif|ico|woff|woff2)$/

function alternativePathsFor(url) {
const paths = []
if (url[url.length - 1] === '/') {
const end = url.length - 1
if (url !== '/') {
paths.push(url.slice(0, end) + '.html')
paths.push(url.slice(0, end) + '.htm')
}
paths.push(url + 'index.html')
paths.push(url + 'index.htm')
} else if (!url.match(assetExtensionRegExp)) {
paths.push(url + '.html')
paths.push(url + '.htm')
paths.push(url + '/index.html')
paths.push(url + '/index.htm')
}

return paths
}

function initializeProxy(port) {
const proxy = httpProxy.createProxyServer({
selfHandleResponse: true,
target: {
host: 'localhost',
port: port
}
})

proxy.on('proxyRes', (proxyRes, req, res) => {
if (proxyRes.statusCode === 404 && req.alternativePaths && req.alternativePaths.length) {
req.url = req.alternativePaths.shift()
return proxy.web(req, res, req.proxyOptions)
}
res.writeHead(proxyRes.statusCode, proxyRes.headers)
proxyRes.on('data', function(data) {
res.write(data)
})
proxyRes.on('end', function() {
res.end()
})
})

return {
web: (req, res, options) => {
req.proxyOptions = options
req.alternativePaths = alternativePathsFor(req.url)
return proxy.web(req, res, options)
}
}
}

async function startProxy(settings, addonUrls) {
const rulesProxy = require("@netlify/rules-proxy");

Expand Down