http: Reuse more http/https Agent code

This commit is contained in:
isaacs
2013-05-22 18:44:24 -07:00
parent 40e92650bb
commit 49519f1217
9 changed files with 128 additions and 86 deletions

View File

@@ -24,6 +24,7 @@ var http = require('http');
var util = require('util');
var url = require('url');
var inherits = require('util').inherits;
var debug = util.debuglog('https');
function Server(opts, requestListener) {
if (!(this instanceof Server)) return new Server(opts, requestListener);
@@ -77,56 +78,58 @@ function createConnection(port, host, options) {
options.host = host;
}
debug('createConnection', options);
return tls.connect(options);
}
function Agent(options) {
http.Agent.call(this, options);
this.defaultPort = 443;
this.protocol = 'https:';
}
inherits(Agent, http.Agent);
Agent.prototype.defaultPort = 443;
Agent.prototype.protocol = 'https:';
Agent.prototype.createConnection = createConnection;
Agent.prototype.getName = function(options) {
var name = http.Agent.prototype.getName.call(this, options);
name += ':';
if (options.ca)
name += options.ca;
name += ':';
if (options.cert)
name += options.cert;
name += ':';
if (options.ciphers)
name += options.ciphers;
name += ':';
if (options.key)
name += options.key;
name += ':';
if (options.pfx)
name += options.pfx;
name += ':';
if (options.rejectUnauthorized !== undefined)
name += options.rejectUnauthorized;
return name;
};
var globalAgent = new Agent();
exports.globalAgent = globalAgent;
exports.Agent = Agent;
exports.request = function(options, cb) {
if (typeof options === 'string') {
options = url.parse(options);
}
if (options.protocol && options.protocol !== 'https:') {
throw new Error('Protocol:' + options.protocol + ' not supported.');
}
options = util._extend({
createConnection: createConnection,
defaultPort: 443
}, options);
if (typeof options.agent === 'undefined') {
if (typeof options.ca === 'undefined' &&
typeof options.cert === 'undefined' &&
typeof options.ciphers === 'undefined' &&
typeof options.key === 'undefined' &&
typeof options.passphrase === 'undefined' &&
typeof options.pfx === 'undefined' &&
typeof options.rejectUnauthorized === 'undefined') {
options.agent = globalAgent;
} else {
options.agent = new Agent(options);
}
}
return new http.ClientRequest(options, cb);
return globalAgent.request(options, cb);
};
exports.get = function(options, cb) {
var req = exports.request(options, cb);
req.end();
return req;
return globalAgent.get(options, cb);
};