Skip to content

Commit

Permalink
feat: support Keep-Alive Header
Browse files Browse the repository at this point in the history
  • Loading branch information
fengmk2 committed Feb 28, 2018
1 parent c828436 commit adccd5e
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
13 changes: 12 additions & 1 deletion app/middleware/meta.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,24 @@

'use strict';

module.exports = options => {
module.exports = (options, app) => {
let server;
app.once('server', s => {
server = s;
});

return async function meta(ctx, next) {
if (options.logging) {
ctx.coreLogger.info('[meta] request started, host: %s, user-agent: %s', ctx.host, ctx.header['user-agent']);
}
await next();
// total response time header
ctx.set('x-readtime', Date.now() - ctx.starttime);

// try to support Keep-Alive Header
if (server && server.keepAliveTimeout && server.keepAliveTimeout >= 1000 && ctx.header.connection !== 'close') {
const timeout = parseInt(server.keepAliveTimeout / 1000);
ctx.set('keep-alive', `timeout=${timeout}`);
}
};
};
26 changes: 26 additions & 0 deletions test/app/middleware/meta.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,30 @@ describe('test/app/middleware/meta.test.js', () => {
assert(content.includes('[meta] request started, host: '));
});
});

describe('cluster start', () => {
let app;
before(() => {
app = utils.cluster('apps/middlewares');
return app.ready();
});
after(() => app.close());

it('should ignore keep-alive header when request is not keep-alive', () => {
return app.httpRequest()
.get('/')
.expect('X-Readtime', /\d+/)
.expect(res => assert(!res.headers['keep-alive']))
.expect(200);
});

it('should return keep-alive header when request is keep-alive', () => {
return app.httpRequest()
.get('/')
.set('connection', 'keep-alive')
.expect('X-Readtime', /\d+/)
.expect('keep-alive', 'timeout=5')
.expect(200);
});
});
});

0 comments on commit adccd5e

Please sign in to comment.