Skip to content

Commit

Permalink
http: lazy create IncomingMessage.headers
Browse files Browse the repository at this point in the history
When rawHeaders is enough don't create the headers object.

PR-URL: #35281
Reviewed-By: Matteo Collina <[email protected]>
Reviewed-By: James M Snell <[email protected]>
  • Loading branch information
ronag authored and BethGriggs committed Dec 15, 2020
1 parent 0de3f56 commit b58725c
Showing 1 changed file with 56 additions and 6 deletions.
62 changes: 56 additions & 6 deletions lib/_http_incoming.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,16 @@
const {
ObjectDefineProperty,
ObjectSetPrototypeOf,
Symbol
} = primordials;

const Stream = require('stream');

const kHeaders = Symbol('kHeaders');
const kHeadersCount = Symbol('kHeadersCount');
const kTrailers = Symbol('kTrailers');
const kTrailersCount = Symbol('kTrailersCount');

function readStart(socket) {
if (socket && !socket._paused && socket.readable)
socket.resume();
Expand Down Expand Up @@ -58,9 +64,11 @@ function IncomingMessage(socket) {
this.httpVersionMinor = null;
this.httpVersion = null;
this.complete = false;
this.headers = {};
this[kHeaders] = null;
this[kHeadersCount] = 0;
this.rawHeaders = [];
this.trailers = {};
this[kTrailers] = null;
this[kTrailersCount] = 0;
this.rawTrailers = [];

this.aborted = false;
Expand Down Expand Up @@ -93,6 +101,44 @@ ObjectDefineProperty(IncomingMessage.prototype, 'connection', {
}
});

ObjectDefineProperty(IncomingMessage.prototype, 'headers', {
get: function() {
if (!this[kHeaders]) {
this[kHeaders] = {};

const src = this.rawHeaders;
const dst = this[kHeaders];

for (let n = 0; n < this[kHeadersCount]; n += 2) {
this._addHeaderLine(src[n + 0], src[n + 1], dst);
}
}
return this[kHeaders];
},
set: function(val) {
this[kHeaders] = val;
}
});

ObjectDefineProperty(IncomingMessage.prototype, 'trailers', {
get: function() {
if (!this[kTrailers]) {
this[kTrailers] = {};

const src = this.rawTrailers;
const dst = this[kTrailers];

for (let n = 0; n < this[kTrailersCount]; n += 2) {
this._addHeaderLine(src[n + 0], src[n + 1], dst);
}
}
return this[kTrailers];
},
set: function(val) {
this[kTrailers] = val;
}
});

IncomingMessage.prototype.setTimeout = function setTimeout(msecs, callback) {
if (callback)
this.on('timeout', callback);
Expand Down Expand Up @@ -131,14 +177,18 @@ function _addHeaderLines(headers, n) {
let dest;
if (this.complete) {
this.rawTrailers = headers;
dest = this.trailers;
this[kTrailersCount] = n;
dest = this[kTrailers];
} else {
this.rawHeaders = headers;
dest = this.headers;
this[kHeadersCount] = n;
dest = this[kHeaders];
}

for (let i = 0; i < n; i += 2) {
this._addHeaderLine(headers[i], headers[i + 1], dest);
if (dest) {
for (let i = 0; i < n; i += 2) {
this._addHeaderLine(headers[i], headers[i + 1], dest);
}
}
}
}
Expand Down

0 comments on commit b58725c

Please sign in to comment.