Skip to content

Instantly share code, notes, and snippets.

@tj
Created February 11, 2011 00:30
Show Gist options
  • Save tj/821692 to your computer and use it in GitHub Desktop.
Save tj/821692 to your computer and use it in GitHub Desktop.
commit 91a46a2a953bd28d534a768968e82355e42b9714
Author: Tj Holowaychuk <tj@vision-media.ca>
Date: Thu Feb 10 16:29:34 2011 -0800
Fixed field merging with progressive fields on writeHead()
diff --git a/lib/http.js b/lib/http.js
index 9506a8c..e109d0b 100644
--- a/lib/http.js
+++ b/lib/http.js
@@ -754,7 +754,7 @@ ServerResponse.prototype.writeContinue = function() {
};
ServerResponse.prototype._implicitHeader = function() {
- this.writeHead(this.statusCode, this._renderHeaders());
+ this.writeHead(this.statusCode);
};
ServerResponse.prototype.writeHead = function(statusCode) {
@@ -769,9 +769,33 @@ ServerResponse.prototype.writeHead = function(statusCode) {
}
if (typeof arguments[headerIndex] == 'object') {
- headers = arguments[headerIndex];
+ // slow-case merge giving precedence to
+ // header fields passed to this method
+ headers = this._renderHeaders();
+ var obj = arguments[headerIndex];
+
+ // handle array case
+ // TODO: remove when array is no longer accepted
+ if (Array.isArray(obj)) {
+ var field;
+ for (var i = 0, len = obj.length; i < len; ++i) {
+ field = obj[i][0];
+ if (field in headers) {
+ obj.push([field, headers[field]]);
+ }
+ }
+ headers = obj;
+ // handle object case
+ } else {
+ var keys = Object.keys(obj),
+ len = keys.length;
+ for (var i = 0; i < len; ++i) {
+ headers[keys[i]] = obj[keys[i]];
+ }
+ }
} else {
- headers = {};
+ // fast-case
+ headers = this._renderHeaders();
}
var statusLine = 'HTTP/1.1 ' + statusCode.toString() + ' ' +
diff --git a/test/simple/test-http-mutable-headers.js b/test/simple/test-http-mutable-headers.js
index 8b44cd0..218c372 100644
--- a/test/simple/test-http-mutable-headers.js
+++ b/test/simple/test-http-mutable-headers.js
@@ -48,6 +48,12 @@ var s = http.createServer(function(req, res) {
res.setHeader('transfer-encoding', 'chunked');
assert.equal(res.getHeader('Transfer-Encoding'), 'chunked');
break;
+
+ case 'writeHead':
+ res.statusCode = 404;
+ res.setHeader('x-foo', 'keyboard cat');
+ res.writeHead(200, { 'x-foo': 'bar', 'x-bar': 'baz' });
+ break;
}
res.statusCode = 201;
@@ -92,6 +98,13 @@ function nextTest () {
case 'transferEncoding':
assert.equal(response.headers['transfer-encoding'], 'chunked');
+ test = 'writeHead';
+ break;
+
+ case 'writeHead':
+ assert.equal(response.headers['x-foo'], 'bar');
+ assert.equal(response.headers['x-bar'], 'baz');
+ assert.equal(200, response.statusCode);
test = 'end';
break;
@@ -114,6 +127,6 @@ function nextTest () {
process.on('exit', function() {
- assert.equal(3, testsComplete);
+ assert.equal(4, testsComplete);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment