[Pkg-javascript-commits] [node-stream-http] 24/208: Lots of fixes plus headers test

Bastien Roucariès rouca at moszumanska.debian.org
Sun Aug 13 13:39:24 UTC 2017


This is an automated email from the git hooks/post-receive script.

rouca pushed a commit to branch master
in repository node-stream-http.

commit 90d812ad44fc1c31b0a61bfdb93ac6d824b23b1d
Author: John Hiesey <john at hiesey.com>
Date:   Tue Jul 7 12:52:25 2015 -0700

    Lots of fixes plus headers test
---
 index.js              | 20 +++++++++++++++-----
 lib/request.js        | 36 +++++++++++++++++++++---------------
 lib/response.js       |  7 +++++--
 test/server/index.js  | 26 +++++++++++++++++++++++++-
 test/tests/headers.js | 46 ++++++++++++++++++++++++++++++++++++++++++++++
 5 files changed, 112 insertions(+), 23 deletions(-)

diff --git a/index.js b/index.js
index 0f450e7..bc3deb5 100644
--- a/index.js
+++ b/index.js
@@ -1,20 +1,31 @@
 var ClientRequest = require('./lib/request')
 var url = require('url')
+var util = require('util')
 
 var http = exports
 
 http.request = function (opts, cb) {
 	if (typeof opts === 'string')
 		opts = url.parse(opts)
+	else
+		opts = util._extend({}, opts)
+
+	// Split opts.host into its components
+	var hostHostname = opts.host ? opts.host.split(':')[0] : null
+	var hostPort = opts.host ? parseInt(opts.host.split(':')[1], 10) : null
 
 	opts.method = opts.method || 'GET'
 	opts.headers = opts.headers || {}
-	opts.protocol = opts.protocol || window.location.protocol
-	opts.hostname = opts.hostname || window.location.hostname
 	opts.path = opts.path || '/'
-	opts.port = opts.port || parseInt(window.location.port, 10)
+	// If the hostname is specified, use that. If it isn't, just let the browser's
+	// logic figure it out
+	opts.hostname = opts.hostname || hostHostname
+	// If port is specified, use that. If it isn't, just let the browser's logic
+	// figure it out; i.e. use port 80/443 for absolute urls and window.location.port
+	// for relative urls
+	opts.port = opts.port || hostPort
 
-	// also valid: port, auth, credentials
+	// Also valid: opts.protocol, opts.auth, opts.credentials
 
 	var req = new ClientRequest(opts)
 	if (cb)
@@ -23,7 +34,6 @@ http.request = function (opts, cb) {
 }
 
 http.get = function get (opts, cb) {
-	opts.method = 'GET'
 	var req = http.request(opts, cb)
 	req.end()
 	return req
diff --git a/lib/request.js b/lib/request.js
index 1e3c213..af03097 100644
--- a/lib/request.js
+++ b/lib/request.js
@@ -31,7 +31,7 @@ var ClientRequest = module.exports = function (opts) {
 
 	self._opts = opts
 	self._body = []
-	self._fullHeaders = {}
+	self._headers = {}
 	foreach(keys(opts.headers), function (name) {
 		self.setHeader(name, opts.headers[name])
 	})
@@ -60,25 +60,32 @@ util.inherits(ClientRequest, stream.Writable)
 
 ClientRequest.prototype.setHeader = function (name, value) {
 	var self = this
-	self._fullHeaders[name.toLowerCase()] = value
+	self._headers[name.toLowerCase()] = {
+		name: name,
+		value: value
+	}
 }
 
 ClientRequest.prototype.getHeader = function (name) {
 	var self = this
-	return self._fullHeaders[name.toLowerCase()]
+	return self._headers[name.toLowerCase()].value
 }
 
 ClientRequest.prototype.removeHeader = function (name) {
 	var self = this
-	delete self._fullHeaders[name.toLowerCase()]
+	delete self._headers[name.toLowerCase()]
 }
 
 ClientRequest.prototype._onFinish = function () {
 	var self = this
 
 	var opts = self._opts
-	var url = opts.protocol + '//' + opts.hostname +
-		(opts.port ? ':' + opts.port : '') + opts.path
+	var url = ''
+	// If hostname is provided, include protocol, hostname, port
+	if (opts.hostname)
+		url = (opts.protocol || '') + '//' + opts.hostname + (opts.port ? (':' + opots.port) : '')
+
+	url += opts.path
 
 	var user, pass
 	if (opts.auth) {
@@ -87,15 +94,14 @@ ClientRequest.prototype._onFinish = function () {
 		pass = authMatch[1]
 	}
 
-	// process and send data
-	var fullHeaders = self._fullHeaders
+	var headersObj = self._headers
 	var body
 	if (opts.method in ['PUT', 'POST']) {
-		if (typeof window.Blob === 'function') {
+		if (util.isFunction(window.Blob)) {
 			body = new window.Blob(self._body.map(function (buffer) {
 				return buffer.toArrayBuffer()
 			}), {
-				type: fullHeaders['content-type'] || ''
+				type: (headersObj['content-type'] || {}).value || ''
 			})
 		} else {
 			// get utf8 string
@@ -104,8 +110,8 @@ ClientRequest.prototype._onFinish = function () {
 	}
 
 	if (self._mode === 'fetch') {
-		var headers = keys(fullHeaders).map(function (name) {
-			return [name, fullHeaders[name]]
+		var headers = keys(headersObj).map(function (name) {
+			return [headersObj[name].name, headersObj[name].value]
 		})
 
 		window.fetch(url, {
@@ -119,7 +125,7 @@ ClientRequest.prototype._onFinish = function () {
 			self._connect()
 		})
 	} else {
-		var xhr = self._xhr = new window.XMLHttpRequest() // TODO: old IE
+		var xhr = self._xhr = new window.XMLHttpRequest()
 		xhr.open(self._opts.method, url, true, user, pass)
 
 		// Can't set responseType on really old browsers
@@ -132,8 +138,8 @@ ClientRequest.prototype._onFinish = function () {
 		if (self._mode === 'text' && 'overrideMimeType' in xhr)
 			xhr.overrideMimeType('text/plain; charset=x-user-defined')
 
-		keys(fullHeaders, function (name) {
-			xhr.setRequestHeader(name, headers[name])
+		foreach(keys(headersObj), function (name) {
+			xhr.setRequestHeader(headersObj[name].name, headersObj[name].value)
 		})
 
 		self._response = null
diff --git a/lib/response.js b/lib/response.js
index 0af0b71..4d65016 100644
--- a/lib/response.js
+++ b/lib/response.js
@@ -30,7 +30,7 @@ var IncomingMessage = exports.IncomingMessage = function (xhr, response, mode) {
 		// for (var <item>,_i,_it = <iterable>[Symbol.iterator](); <item> = (_i = _it.next()).value,!_i.done;)
 		for (var header, _i, _it = response.headers[Symbol.iterator](); header = (_i = _it.next()).value, !_i.done;) {
 			self.headers[header[0].toLowerCase()] = header[1]
-			self.rawHeaders.push(header)
+			self.rawHeaders.push(header[0], header[1])
 		}
 
 		// TODO: this doesn't respect backpressure. Once WritableStream is available, this can be fixed
@@ -59,7 +59,10 @@ var IncomingMessage = exports.IncomingMessage = function (xhr, response, mode) {
 			var matches = header.match(/^([^:]+):\s*(.*)/)
 			if (matches) {
 				var key = matches[1].toLowerCase()
-				self.headers[key.toLowerCase()] = matches[2] // TODO: some headers should use commas, some arrays
+				if (!util.isUndefined(self.headers[key]))
+					self.headers[key] += ', ' + matches[2]
+				else
+					self.headers[key] = matches[2]
 				self.rawHeaders.push(matches[1], matches[2])
 			}
 		})
diff --git a/test/server/index.js b/test/server/index.js
index ad546ec..9d04290 100644
--- a/test/server/index.js
+++ b/test/server/index.js
@@ -20,6 +20,30 @@ var copiesMimeTypes = {
 
 var maxDelay = 5000 // ms
 
+app.use('/testHeaders', function (req, res, next) {
+	var parsed = url.parse(req.url, true)
+
+	// Values in query parameters are sent as response headers
+	Object.keys(parsed.query).forEach(function (key) {
+		res.setHeader('Test-' + key, parsed.query[key])
+	})
+
+	res.setHeader('Content-Type', 'application/json')
+
+	// Request headers are sent in the body as json
+	var reqHeaders = {}
+	Object.keys(req.headers).forEach(function (key) {
+		key = key.toLowerCase()
+		if (key.indexOf('test-') === 0)
+			reqHeaders[key] = req.headers[key]
+	})
+
+	var body = JSON.stringify(reqHeaders)
+	res.setHeader('Content-Length', body.length)
+	res.write(body)
+	res.end()
+})
+
 app.use(function (req, res, next) {
 	var parsed = url.parse(req.url, true)
 
@@ -60,5 +84,5 @@ app.use(function (req, res, next) {
 app.use(express.static(path.join(__dirname, 'static')))
 
 var port = parseInt(process.env.ZUUL_PORT) || 8199
-console.log('server listening on port', port)
+console.log('Test server listening on port', port)
 server.listen(port)
diff --git a/test/tests/headers.js b/test/tests/headers.js
new file mode 100644
index 0000000..72dbc6a
--- /dev/null
+++ b/test/tests/headers.js
@@ -0,0 +1,46 @@
+var Buffer = require('buffer').Buffer
+var fs = require('fs');
+var test = require('tape')
+
+var http = require('../..')
+
+test('headers', function (t) {
+	http.get({
+		path: '/testHeaders?Response-Header=bar&Response-Header-2=BAR2',
+		headers: {
+			'Test-Request-Header': 'foo',
+			'Test-Request-Header-2': 'FOO2'
+		}
+	}, function (res) {
+		var rawHeaders = []
+		for (var i = 0; i < res.rawHeaders.length; i += 2) {
+			var lowerKey = res.rawHeaders[i].toLowerCase()
+			if (lowerKey.indexOf('test-') === 0)
+				rawHeaders.push(lowerKey, res.rawHeaders[i + 1])
+		}
+		var header1Pos = rawHeaders.indexOf('test-response-header')
+		t.ok(header1Pos >= 0, 'raw response header 1 present')
+		t.equal(rawHeaders[header1Pos + 1], 'bar', 'raw response header value 1')
+		var header2Pos = rawHeaders.indexOf('test-response-header-2')
+		t.ok(header2Pos >= 0, 'raw response header 2 present')
+		t.equal(rawHeaders[header2Pos + 1], 'BAR2', 'raw response header value 2')
+		t.equal(rawHeaders.length, 4, 'correct number of raw headers')
+
+		t.equal(res.headers['test-response-header'], 'bar', 'response header 1')
+		t.equal(res.headers['test-response-header-2'], 'BAR2', 'response header 2')
+
+		var buffers = []
+
+		res.on('end', function () {
+			var body = JSON.parse(Buffer.concat(buffers).toString())
+			t.equal(body['test-request-header'], 'foo', 'request header 1')
+			t.equal(body['test-request-header-2'], 'FOO2', 'request header 2')
+			t.equal(Object.keys(body).length, 2, 'correct number of request headers')
+			t.end()
+		})
+
+		res.on('data', function (data) {
+			buffers.push(data)
+		})
+	})
+})
\ No newline at end of file

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-javascript/node-stream-http.git



More information about the Pkg-javascript-commits mailing list