koa-lite/examples/simple.js

49 lines
848 B
JavaScript
Raw Permalink Normal View History

2013-08-17 07:15:57 +00:00
var koa = require('..');
var app = koa();
// x-response-time
app.use(function *responseTime(next){
var start = new Date;
yield next;
var ms = new Date - start;
this.set('X-Response-Time', ms + 'ms');
2013-08-17 07:15:57 +00:00
});
// logger
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);
2013-08-17 07:15:57 +00:00
});
// content-length
app.use(function *contentLength(next){
yield next;
if (!this.body) return;
this.set('Content-Length', Buffer.byteLength(this.body));
2013-08-17 07:15:57 +00:00
});
2013-08-28 05:42:05 +00:00
// custom 404 handler
2013-08-17 07:15:57 +00:00
app.use(function *notfound(next){
yield next;
if (this.body) return;
this.status = 404;
this.body = 'Sorry! No luck';
2013-08-17 07:15:57 +00:00
});
2013-08-28 05:42:05 +00:00
// response
2013-08-17 07:15:57 +00:00
app.use(function *response(next){
yield next;
if ('/' != this.url) return;
this.body = 'Hello World';
2013-08-17 07:15:57 +00:00
});
2013-08-28 02:57:16 +00:00
app.listen(3000);