Improve API for setting max request limit

Renamed the key to "max-request-size" and allow units to be provided
rather than just a number. The default is now 1MB.
This commit is contained in:
Aron Carroll 2012-10-27 18:11:52 +01:00
parent fd3493da4d
commit 2caed53c1c
3 changed files with 30 additions and 7 deletions

View File

@ -7,9 +7,7 @@
"ssl": false,
"static": false
},
"bin": {
"max-size": 1572864
},
"max-request-size": "1MB",
"store": {
"adapter": "sqlite",
"sqlite": {

View File

@ -128,7 +128,7 @@ app.connect = function (callback) {
}
app.use(mount, express.static(path.join(app.set('root'), 'public')));
app.use(middleware.limitContentLength({limit: app.set('bin max-size')}));
app.use(middleware.limitContentLength({limit: app.set('max-request-size')}));
app.use(express.cookieParser(app.set('session secret')));
app.use(express.cookieSession({key: 'jsbin'}));
app.use(express.urlencoded());

View File

@ -123,12 +123,37 @@ module.exports = {
// Limit the file size that can be uploaded.
limitContentLength: function (options) {
var powers = { k: 1, m: 2, g: 3, t: 4 },
regexp = /^(\d+(?:.\d+)?)\s*([kmgt]?)b?$/;
// Parse a string representing a file size and convert it into bytes.
// A number on it's own will be assumed to be bytes. A multiple such as
// "k" or "m" can be appended to the string to handle larger numbers. This
// is case insensitive and uses powers of 1024 rather than (1000).
// So both 1kB and 1kb == 1024.
function parseLimit(string) {
var matches = ('' + string).toLowerCase().match(regexp),
bytes = null, power;
if (matches) {
bytes = parseFloat(matches[1]);
power = powers[matches[2]];
if (bytes && power) {
bytes = Math.pow(bytes * 1024, power);
}
}
return bytes || null;
}
return function (req, res, next) {
if (options && options.limit) {
var contentLength = parseInt(req.header('Content-Length', 0), 10),
message = 'Sorry, the content you have uploaded is larger than JS Bin can handle. Max size is ' + options.limit + ' bytes';
var limit = options.limit && parseLimit(options.limit),
contentLength = parseInt(req.header('Content-Length', 0), 10),
message = 'Sorry, the content you have uploaded is larger than JS Bin can handle. Max size is ' + options.limit;
if (contentLength > options.limit) {
if (limit && contentLength > limit) {
return next(new errors.RequestEntityTooLarge(message));
}
}