Skip to content

Commit

Permalink
feat: support Keep-Alive Header (#2146)
Browse files Browse the repository at this point in the history
  • Loading branch information
fengmk2 authored and popomore committed Feb 28, 2018
1 parent c828436 commit a739002
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
7 changes: 7 additions & 0 deletions app/middleware/meta.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,12 @@ module.exports = options => {
await next();
// total response time header
ctx.set('x-readtime', Date.now() - ctx.starttime);

// try to support Keep-Alive Header
const server = ctx.app.server;
if (server && server.keepAliveTimeout && server.keepAliveTimeout >= 1000 && ctx.header.connection !== 'close') {
const timeout = parseInt(server.keepAliveTimeout / 1000);
ctx.set('keep-alive', `timeout=${timeout}`);
}
};
};
6 changes: 6 additions & 0 deletions lib/application.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@ class Application extends EggApplication {
options.type = 'application';
super(options);

// will auto set after 'server' event emit
this.server = null;

try {
this.loader.load();
} catch (e) {
Expand Down Expand Up @@ -83,6 +86,9 @@ class Application extends EggApplication {
}

onServer(server) {
// expose app.server
this.server = server;

/* istanbul ignore next */
graceful({
server: [ server ],
Expand Down
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 a739002

Please sign in to comment.