This repository was archived by the owner on Jan 27, 2019. It is now read-only.
forked from koajs/examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
50 lines (40 loc) · 1.36 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
var compose = require('koa-compose');
var koa = require('koa');
var app = module.exports = koa();
// virtual host apps
var wwwSubdomain = composer(require('./apps/koa'));
var barSubdomain = composer(require('./apps/array'));
// compose koa apps and middleware arrays
// to be used later in our host switch generator
function composer(app) {
var middleware = app instanceof koa ? app.middleware : app;
return compose(middleware);
}
// look ma, global response logging for all our apps!
app.use(function *(next) {
var start = new Date;
yield next;
var ms = new Date - start;
if ('test' != process.env.NODE_ENV) {
console.log('%s %s %s - %sms', this.host, this.method, this.url, ms);
}
});
// switch between appropriate hosts calling their
// composed middleware with the appropriate context.
app.use(function *(next) {
switch (this.host) {
case 'example.com':
case 'www.example.com':
// displays `Hello from main app`
// and sets a `X-Custom` response header
return yield wwwSubdomain.call(this, next);
case 'bar.example.com':
// displays `Howzit? From bar middleware bundle`
// and sets a `X-Response-Time` response header
return yield barSubdomain.call(this, next);
}
// everything else, eg: 127.0.0.1:3000
// will propagate to 404 Not Found
return yield next;
});
if (!module.parent) app.listen(3000);