Skip to content

Commit

Permalink
backport: #2146 support Keep-Alive Header
Browse files Browse the repository at this point in the history
  • Loading branch information
fengmk2 authored and atian25 committed Apr 3, 2019
1 parent 328cbf2 commit 22eef57
Show file tree
Hide file tree
Showing 3 changed files with 40 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 @@ -9,5 +9,12 @@ module.exports = () => {
yield next;
// total response time header
this.set('x-readtime', Date.now() - this.starttime);

// try to support Keep-Alive Header
const server = this.app.server;
if (server && server.keepAliveTimeout && server.keepAliveTimeout >= 1000 && this.header.connection !== 'close') {
const timeout = parseInt(server.keepAliveTimeout / 1000);
this.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 @@ -47,6 +47,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 @@ -85,6 +88,9 @@ class Application extends EggApplication {
}

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

/* istanbul ignore next */
graceful({
server: [ server ],
Expand Down
27 changes: 27 additions & 0 deletions test/app/middleware/meta.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use strict';

const mm = require('egg-mock');
const assert = require('assert');
const utils = require('../../utils');

describe('test/app/middleware/meta.test.js', () => {
Expand All @@ -20,4 +21,30 @@ describe('test/app/middleware/meta.test.js', () => {
.expect('X-Readtime', /\d+/)
.expect(200);
});

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 22eef57

Please sign in to comment.