Skip to content

Commit

Permalink
Parse request in a different way
Browse files Browse the repository at this point in the history
  • Loading branch information
leo committed May 19, 2018
1 parent 06e231a commit db41f81
Showing 1 changed file with 30 additions and 18 deletions.
48 changes: 30 additions & 18 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ const appendHeaders = (target, source) => {
}
};

const getHeaders = async (handlers, customHeaders = [], {relative, absolute}) => {
const getHeaders = async (handlers, customHeaders = [], relativePath, stats) => {
const related = {};

if (customHeaders.length > 0) {
Expand All @@ -119,16 +119,14 @@ const getHeaders = async (handlers, customHeaders = [], {relative, absolute}) =>
for (let index = 0; index < customHeaders.length; index++) {
const {source, headers} = customHeaders[index];

if (sourceMatches(source, relative)) {
if (sourceMatches(source, relativePath)) {
appendHeaders(related, headers);
}
}
}

const stats = await handlers.stat(absolute);

const defaultHeaders = {
'Content-Type': mime.getType(relative),
'Content-Type': mime.getType(relativePath),
'Last-Modified': stats.mtime.toUTCString(),
'Content-Length': stats.size
};
Expand All @@ -142,8 +140,8 @@ module.exports = async (request, response, config = {}, methods = {}) => {
const handlers = getHandlers(methods);

const {pathname} = url.parse(request.url);
const rewrittenURL = applyRewrites(pathname, config.rewrites);
const redirect = shouldRedirect(rewrittenURL, config.redirects);
const relativePath = applyRewrites(decodeURIComponent(pathname), config.rewrites);
const redirect = shouldRedirect(relativePath, config.redirects);

if (redirect) {
response.writeHead(redirect.statusCode, {
Expand All @@ -153,21 +151,35 @@ module.exports = async (request, response, config = {}, methods = {}) => {
response.end();
}

const related = decodeURIComponent(path.join(current, rewrittenURL));
const relatedExists = await fs.exists(related);
const absolutePath = path.join(current, relativePath);
let stats = null;

if (relatedExists) {
const headers = await getHeaders(handlers, config.headers, {
relative: rewrittenURL,
absolute: related
});
try {
stats = await handlers.stat(absolutePath);
} catch (err) {
if (err.code !== 'ENOENT') {
response.statusCode = 500;
response.end(err.message);

response.writeHead(200, headers);
handlers.createReadStream(related).pipe(response);
return;
}
}

if (!stats) {
response.statusCode = 404;
response.end('Not Found');

return;
}

response.statusCode = 404;
response.end('Not Found');
const headers = await getHeaders(handlers, config.headers, relativePath, stats);

if (stats.isFile()) {
response.writeHead(200, headers);
handlers.createReadStream(absolutePath).pipe(response);
return;
}

response.statusCode = 200;
response.end('Directory');
};

0 comments on commit db41f81

Please sign in to comment.