2013-08-28 02:48:58 +00:00
|
|
|
|
|
|
|
var zlib = require('zlib');
|
|
|
|
var koa = require('..');
|
|
|
|
var fs = require('fs');
|
|
|
|
var app = koa();
|
|
|
|
|
|
|
|
// ignore favicons
|
|
|
|
|
2013-11-08 09:13:43 +00:00
|
|
|
app.use(function *(next){
|
|
|
|
if ('/favicon.ico' == this.path) this.status = 404;
|
|
|
|
yield next;
|
2013-08-28 02:48:58 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
// logger
|
|
|
|
|
2013-11-08 09:13:43 +00:00
|
|
|
app.use(function *(next){
|
|
|
|
console.log('%s %s', this.method, this.url);
|
|
|
|
yield next;
|
2013-08-28 02:48:58 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
// stream a file
|
|
|
|
|
2013-11-08 09:13:43 +00:00
|
|
|
app.use(function *(next){
|
|
|
|
var path = __dirname + this.path;
|
|
|
|
var exists = yield isFile(path);
|
2013-08-28 02:48:58 +00:00
|
|
|
|
2013-11-08 09:13:43 +00:00
|
|
|
if (!exists) return yield next;
|
2013-08-28 02:48:58 +00:00
|
|
|
|
2013-11-08 09:13:43 +00:00
|
|
|
this.body = fs.createReadStream(path);
|
|
|
|
yield next;
|
2013-08-28 02:48:58 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
// gzip the response
|
|
|
|
|
2013-11-08 09:13:43 +00:00
|
|
|
app.use(function *(next){
|
|
|
|
var body = this.body;
|
2013-08-28 02:56:35 +00:00
|
|
|
|
2013-11-08 09:13:43 +00:00
|
|
|
if (!body || !body.readable) return yield next;
|
2013-08-28 02:56:35 +00:00
|
|
|
|
2013-11-08 09:13:43 +00:00
|
|
|
var gzip = zlib.createGzip();
|
|
|
|
this.set('Content-Encoding', 'gzip');
|
|
|
|
this.body = gzip;
|
|
|
|
body.pipe(gzip);
|
2013-08-28 02:48:58 +00:00
|
|
|
|
2013-11-08 09:13:43 +00:00
|
|
|
yield next;
|
2013-08-28 02:48:58 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
app.listen(3000);
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Stat regular file helper.
|
|
|
|
*/
|
|
|
|
|
|
|
|
function isFile(file) {
|
|
|
|
return function(done){
|
|
|
|
fs.stat(file, function(err, stat){
|
|
|
|
if (err && 'ENOENT' == err.code) return done(null, false);
|
|
|
|
if (err) return done(err);
|
|
|
|
done(null, stat.isFile());
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|