Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

http: add new functions to OutgoingMessage #10805

Merged
merged 1 commit into from
Feb 20, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions doc/api/http.md
Original file line number Diff line number Diff line change
Expand Up @@ -934,6 +934,66 @@ Example:
var contentType = response.getHeader('content-type');
```

### response.getHeaderNames()
<!-- YAML
added: REPLACEME
-->

* Returns: {Array}

Returns an array containing the unique names of the current outgoing headers.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we really need unique here?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, because header names can be repeated in the outoing headers, which could cause duplicate values in this Array, but it doesn't, the Array can be relied on to be unique.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @sam-github :-)

All header names are lowercase.

Example:

```js
response.setHeader('Foo', 'bar');
response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);

var headerNames = response.getHeaderNames();
// headerNames === ['foo', 'set-cookie']
```

### response.getHeaders()
<!-- YAML
added: REPLACEME
-->

* Returns: {Object}

Returns a shallow copy of the current outgoing headers. Since a shallow copy
is used, array values may be mutated without additional calls to various
header-related http module methods. The keys of the returned object are the
header names and the values are the respective header values. All header names
are lowercase.

Example:

```js
response.setHeader('Foo', 'bar');
response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);

var headers = response.getHeaders();
// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] }
```
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Out of curiosity: did you investigate the possibility of having a variation on this that returns an iterator instead? Not sure if that would perform better or worse than a copy if we allowed it to do a live iteration. Obviously it depends entirely on how we expect users to make use of this.

Also, a response.hasHeader(name) that returns boolean might be worthwhile for the cases someone wishes to simply check that a header exists.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I thought about the iterator, but I'm not sure if the performance is up to par with existing solutions.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll experiment with it a bit and see what I get

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added hasHeader().


### response.hasHeader(name)
Copy link
Contributor

@silverwind silverwind Feb 1, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this necessary? One could just do response.getHeaderNames().includes(name).

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As a performance optimization when simply checking for the existence of a header, hasHeader is preferred.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep.

<!-- YAML
added: REPLACEME
-->

* `name` {String}
* Returns: {Boolean}

Returns `true` if the header identified by `name` is currently set in the
outgoing headers. Note that the header name matching is case-insensitive.

Example:

```js
var hasContentType = response.hasHeader('content-type');
```

### response.headersSent
<!-- YAML
added: v0.9.3
Expand Down
35 changes: 35 additions & 0 deletions lib/_http_outgoing.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ var RE_FIELDS = new RegExp('^(?:Connection|Transfer-Encoding|Content-Length|' +
var RE_CONN_VALUES = /(?:^|\W)close|upgrade(?:$|\W)/ig;
var RE_TE_CHUNKED = common.chunkExpression;

// Used to store headers returned by getHeaders()
function OutgoingHeaders() {}
OutgoingHeaders.prototype = Object.create(null);

var dateCache;
function utcDate() {
if (!dateCache) {
Expand Down Expand Up @@ -426,6 +430,37 @@ OutgoingMessage.prototype.getHeader = function getHeader(name) {
};


// Returns an array of the names of the current outgoing headers.
OutgoingMessage.prototype.getHeaderNames = function getHeaderNames() {
return (this._headers ? Object.keys(this._headers) : []);
};


// Returns a shallow copy of the current outgoing headers.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks like a deep copy to me, what am I missing?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's not. Array values are no longer copied.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok, so then in the docs above we need to warn that the return value should not be modified, right? Or is it deliberately supported, modifying the array values?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

and I really misread the code 😊 I thought I saw two loops.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's just matching getHeader() behavior.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can't speak about the origin of getHeader(), but to me explicitly stating a shallow copy is made in this new function implies that being able to add/remove to/from array values is intentional.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK, so my request is that that implication be stated in the docs, so people don't think its like #10795, an unfortunate loop-hole, that will be closed in the future, and that they should not depend on.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think #10795 is a different situation. There is arguably less usefulness in mutating the list of ciphers/hashes supported by OpenSSL. Mutating the array values in this PR is more useful because you do not have to continually execute setHeader(), which has additional overhead, when you want to add more values for that header.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree it is different. I just want it stated in the docs, rather than "implied" (your word). I suggest you include what you just wrote:

The array values can be mutated, which is useful because you do not have to continually execute setHeader(), which has additional overhead, when you want to add more values for that header.

You seem dead set against adding an explanatory sentence, because you feel the user should be able to derive this understanding from the word "shallow" (if I understand you correctly), but I don't think one extra sentence is overkill here.

Copy link
Contributor Author

@mscdex mscdex Feb 17, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@sam-github It's added now... LGTY?

OutgoingMessage.prototype.getHeaders = function getHeaders() {
const headers = this._headers;
const ret = new OutgoingHeaders();
if (headers) {
const keys = Object.keys(headers);
for (var i = 0; i < keys.length; ++i) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there any reason this can't be an Object.assign or util._extend?

Copy link
Contributor Author

@mscdex mscdex Jan 24, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Performance. Last we checked, Object.assign() is still atrociously slow. Also, it's simple enough to inline a copy implementation here.

const key = keys[i];
const val = headers[key][1];
ret[key] = val;
}
}
return ret;
};


OutgoingMessage.prototype.hasHeader = function hasHeader(name) {
if (typeof name !== 'string') {
throw new TypeError('"name" argument must be a string');
}

return !!(this._headers && this._headers[name.toLowerCase()]);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This would return true for constructor, __proto__, right?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Technically yes, but that's nothing new.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A has function returning true for something which is actually not there doesn't feel right. Strictly speaking, those inherited properties are not headers.

Copy link
Contributor Author

@mscdex mscdex Jan 28, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You could make the same argument for the already existing getHeader(). I'm not sure it's best to have a difference in functionality between the two, especially since I'd like to be able to backport these additions and if we changed the behavior (of getHeader()), this PR would be semver-major then.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess we can fix it a separate PR.

};


OutgoingMessage.prototype.removeHeader = function removeHeader(name) {
if (typeof name !== 'string') {
throw new TypeError('"name" argument must be a string');
Expand Down
46 changes: 45 additions & 1 deletion test/parallel/test-http-mutable-headers.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,13 @@ const cookies = [
const s = http.createServer(common.mustCall((req, res) => {
switch (test) {
case 'headers':
// Check that header-related functions work before setting any headers
// eslint-disable-next-line no-restricted-properties
assert.deepEqual(res.getHeaders(), {});
assert.deepStrictEqual(res.getHeaderNames(), []);
assert.deepStrictEqual(res.hasHeader('Connection'), false);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These two need not be deep?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perhaps not the hasHeader(), but I think it would be good to leave it for object comparisons (including arrays).

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, object comparisons are fine. I meant this line and the next one.

assert.deepStrictEqual(res.getHeader('Connection'), undefined);

assert.throws(() => {
res.setHeader();
}, /^TypeError: Header name must be a valid HTTP Token \["undefined"\]$/);
Expand All @@ -34,15 +41,52 @@ const s = http.createServer(common.mustCall((req, res) => {
res.removeHeader();
}, /^TypeError: "name" argument must be a string$/);

const arrayValues = [1, 2, 3];
res.setHeader('x-test-header', 'testing');
res.setHeader('X-TEST-HEADER2', 'testing');
res.setHeader('set-cookie', cookies);
res.setHeader('x-test-array-header', [1, 2, 3]);
res.setHeader('x-test-array-header', arrayValues);

assert.strictEqual(res.getHeader('x-test-header'), 'testing');
assert.strictEqual(res.getHeader('x-test-header2'), 'testing');

const headersCopy = res.getHeaders();
// eslint-disable-next-line no-restricted-properties
assert.deepEqual(headersCopy, {
'x-test-header': 'testing',
'x-test-header2': 'testing',
'set-cookie': cookies,
'x-test-array-header': arrayValues
});
// eslint-disable-next-line no-restricted-properties
assert.deepEqual(headersCopy['set-cookie'], cookies);
assert.strictEqual(headersCopy['x-test-array-header'], arrayValues);

assert.deepStrictEqual(res.getHeaderNames(),
['x-test-header', 'x-test-header2',
'set-cookie', 'x-test-array-header']);

assert.strictEqual(res.hasHeader('x-test-header2'), true);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: being pedantic here but it would be good to expand the test to include mixed case header name (to ensure the toLowerCase) and passing non-string inputs to test the error checking.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added.

assert.strictEqual(res.hasHeader('X-TEST-HEADER2'), true);
assert.strictEqual(res.hasHeader('X-Test-Header2'), true);
assert.throws(() => {
res.hasHeader();
}, /^TypeError: "name" argument must be a string$/);
assert.throws(() => {
res.hasHeader(null);
}, /^TypeError: "name" argument must be a string$/);
assert.throws(() => {
res.hasHeader(true);
}, /^TypeError: "name" argument must be a string$/);
assert.throws(() => {
res.hasHeader({ toString: () => 'X-TEST-HEADER2' });
}, /^TypeError: "name" argument must be a string$/);

res.removeHeader('x-test-header2');

assert.strictEqual(res.hasHeader('x-test-header2'), false);
assert.strictEqual(res.hasHeader('X-TEST-HEADER2'), false);
assert.strictEqual(res.hasHeader('X-Test-Header2'), false);
break;

case 'contentLength':
Expand Down