Skip to content

Instantly share code, notes, and snippets.

@gergelyke
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gergelyke/efdb93a6c266a0ebbebf to your computer and use it in GitHub Desktop.
Save gergelyke/efdb93a6c266a0ebbebf to your computer and use it in GitHub Desktop.
Koa middlewares
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);
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);
});
@oroce
Copy link

oroce commented May 12, 2014

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment