koa-lite/examples/simple.js

60 lines
1 KiB
JavaScript
Raw Permalink Normal View History

2013-08-17 07:15:57 +00:00
var http = require('http');
var koa = require('..');
var app = koa();
// x-response-time
app.use(function(next){
2013-08-29 04:05:35 +00:00
return function *responseTime(){
2013-08-17 07:15:57 +00:00
var start = new Date;
yield next;
var ms = new Date - start;
this.set('X-Response-Time', ms + 'ms');
}
});
// logger
app.use(function(next){
2013-08-29 04:05:35 +00:00
return function *logger(){
2013-08-17 07:15:57 +00:00
var start = new Date;
yield next;
var ms = new Date - start;
console.log('%s %s - %s', this.method, this.url, ms);
}
});
// content-length
app.use(function(next){
2013-08-29 04:05:35 +00:00
return function *contentLength(){
2013-08-17 07:15:57 +00:00
yield next;
2013-08-28 05:42:05 +00:00
if (!this.body) return;
2013-08-17 07:15:57 +00:00
this.set('Content-Length', Buffer.byteLength(this.body));
}
});
2013-08-28 05:42:05 +00:00
// custom 404 handler
2013-08-17 07:15:57 +00:00
app.use(function(next){
2013-08-29 04:05:35 +00:00
return function *notfound(){
2013-08-17 07:15:57 +00:00
yield next;
2013-08-28 05:42:05 +00:00
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(next){
2013-08-29 04:05:35 +00:00
return function *response(){
2013-08-17 07:15:57 +00:00
yield next;
2013-08-28 05:42:05 +00:00
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);