-
Notifications
You must be signed in to change notification settings - Fork 75
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Karl Morrison
committed
Sep 22, 2016
1 parent
4ab2321
commit b6319a3
Showing
1 changed file
with
70 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,70 @@ | ||
require('raptor-polyfill/string/startsWith'); | ||
require('raptor-polyfill/string/endsWith'); | ||
|
||
var lasso = require('../'); | ||
var send = require('send'); | ||
var extend = require('raptor-util/extend'); | ||
|
||
function notFound() { | ||
this.error(404); | ||
} | ||
|
||
module.exports = function(options) { | ||
options = options || {}; | ||
|
||
var myLasso = options.lasso || lasso.getDefaultLasso(); | ||
var config = myLasso.config; | ||
|
||
var outputDir = config.outputDir; | ||
var urlPrefix = config.urlPrefix; | ||
var routePrefix = urlPrefix; | ||
if (!routePrefix.endsWith('/')) { | ||
routePrefix += '/'; | ||
} | ||
|
||
if (!outputDir || !urlPrefix) { | ||
return function(req, res, next) { | ||
return next(); | ||
}; | ||
} | ||
|
||
var sendOptions = { | ||
fallthrough: false, | ||
redirect: false, | ||
index: false | ||
}; | ||
|
||
if (options.sendOptions) { | ||
extend(sendOptions, options.sendOptions); | ||
} | ||
|
||
sendOptions.root = outputDir; | ||
|
||
|
||
return function(ctx, next) { | ||
var req = ctx.request, | ||
res = ctx.response; | ||
|
||
var path = req.path; | ||
if (!path.startsWith(routePrefix) || (req.method !== 'GET' && req.method !== 'HEAD')) { | ||
return next(); | ||
} | ||
|
||
var filePath = path.substring(routePrefix.length); | ||
|
||
// create send stream | ||
var stream = send(req, filePath, sendOptions); | ||
|
||
// add directory handler | ||
stream.on('directory', notFound); | ||
|
||
// forward errors | ||
stream.on('error', function error(err) { | ||
res.statusCode = err.statusCode || 500; | ||
res.end('Not found: ' + filePath); | ||
}); | ||
|
||
// pipe | ||
stream.pipe(res); | ||
}; | ||
}; |