Last active
August 29, 2015 14:01
-
-
Save gergelyke/efdb93a6c266a0ebbebf to your computer and use it in GitHub Desktop.
Koa middlewares
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
var koa = require('koa'); | |
var app = koa(); | |
app.use(function *responseTime(next){ | |
var start = new Date; | |
yield next; | |
var ms = new Date - start; | |
this.set('X-Response-Time', ms + 'ms'); | |
}); | |
app.use(function *logger(next){ | |
var start = new Date; | |
yield next; | |
var ms = new Date - start; | |
console.log('%s %s - %s', this.method, this.url, ms); | |
}); | |
app.use(function *response(next){ | |
yield next; | |
this.body = 'Hello Nodebp!' | |
}); | |
app.listen(3000); |
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
var express = require('express'); | |
var app = express(); | |
app.use(function responseTime(req, res) { | |
var start = new Date(); | |
var end = res.end; | |
res.end = function() { | |
var ms = new Date() - start; | |
res.set('X-Response-Time', ms + 'ms'); | |
end.apply(res,arguments); | |
}; | |
req.next(); | |
}); | |
app.use(function logger(req, res) { | |
var start = new Date(); | |
var end = res.end; | |
res.end = function() { | |
var ms = new Date() - start; | |
console.log('%s %s - %s', req.method, req.url, ms); | |
end.apply(res,arguments); | |
}; | |
req.next(); | |
}); | |
app.use(function response(req, res){ | |
res.send('Hello Nodebp!'); | |
}); | |
var server = app.listen(3000, function() { | |
console.log('Listening on port %d', server.address().port); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
express version of this: https://gist.github.com/oroce/03349e92eb0f6d282d0e