Skip to content

Commit

Permalink
Avoid overriding headers set in onresponse
Browse files Browse the repository at this point in the history
Currently, overriding a header from the target response in the source
response requires doing it in both ondata_response (when receiving the first
chunk of data) and in onend_response (for when the response doesn't contain
any data), after verifying that res.headersSent is false. That's clumsy at
best.

By filtering the copied headers with those already present in the source
response, it's possible to set them in onresponse once and for all.
  • Loading branch information
fpavageau committed Dec 24, 2019
1 parent 2ac4ca6 commit 1ee98fd
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
4 changes: 3 additions & 1 deletion lib/plugins-middleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -362,7 +362,9 @@ function handleTargetResponse(targetRequest, targetResponse, options, cb) {
Object.keys(targetResponse.headers).forEach(function(header) {
// skip setting the 'connection: keep-alive' header
// setting it causes gateway to not accept any more connections
if (header !== 'connection') {
// Headers that have been set in onresponse are also skipped to let the plugins override those from the
// target response.
if (header !== 'connection' && !sourceResponse.hasHeader(header)) {
sourceResponse.setHeader(header, targetResponse.headers[header]);
}
});
Expand Down
21 changes: 21 additions & 0 deletions tests/plugin-lifecycle-tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,27 @@ describe('test lifecycle events', function() {
});
});
});

it('should keep the header set on the source response', function(done) {
this.timeout(20000);
const testPlugin = TestPlugin((type, data, cb) => cb());
const handler = testPlugin.init();
handler.onresponse = (sourceReq, sourceRes, targetRes, data, next) => {
sourceRes.setHeader('content-type', 'application/octet-stream');
sourceRes.setHeader('original-content-type', targetRes.headers['content-type']);
next();
};
gateway.addPlugin('test', () => handler);

gateway.start((err) => {
assert(!err, err);
request({ method: 'GET', url: 'http://localhost:' + gatewayPort + '/v1/echo/get' }, (err, r) => {
assert.equal(r.headers['content-type'], 'application/octet-stream');
assert.equal(r.headers['original-content-type'], 'application/json');
done();
});
});
});
});

function _findHeaders(headers, expectedHeaders) {
Expand Down

0 comments on commit 1ee98fd

Please sign in to comment.