-
Notifications
You must be signed in to change notification settings - Fork 0
/
http-proxy-agent.js
88 lines (75 loc) · 1.92 KB
/
http-proxy-agent.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/**
* Module dependencies.
* @see https://gist.github.com/TooTallNate/5952254
*/
var net = require('net');
var tls = require('tls');
var url = require('url');
var Agent = require('./agent');
var inherits = require('util').inherits;
/**
* Module exports.
*/
module.exports = HttpProxyAgent;
/**
* The `HttpProxyAgent` implements an HTTP Agent subclass that connects to the
* specified "HTTP proxy server" in order to proxy HTTP requests.
*
* @api public
*/
function HttpProxyAgent (opts) {
if (!(this instanceof HttpProxyAgent)) return new HttpProxyAgent(opts);
if ('string' == typeof opts) opts = url.parse(opts);
Agent.call(this);
this.proxy = opts;
this.secure = this.proxy.protocol && this.proxy.protocol == 'https:';
}
inherits(HttpProxyAgent, Agent);
/**
* Called when the node-core HTTP client library is creating a new HTTP request.
*
* @api public
*/
HttpProxyAgent.prototype.addRequest = function (req, host, port, localAddress) {
var opts;
if ('object' == typeof host) {
// >= v0.11.x API
opts = host;
} else {
// <= v0.10.x API
opts = {
host: host,
port: port,
localAddress: localAddress
};
}
// change the `http.ClientRequest` instance's "path" field
// to the absolute path of the URL that will be requested
var absolute = url.format({
protocol: 'http:',
hostname: opts.hostname || opts.host,
port: opts.port,
pathname: req.path
});
req.path = absolute;
Agent.prototype.addRequest.apply(this, arguments);
};
/**
* Initiates a TCP connection to the specified HTTP proxy server.
*
* @api public
*/
HttpProxyAgent.prototype.createConnection = function (opts, fn) {
var socket;
var info = {
host: this.proxy.hostname || this.proxy.host,
port: +this.proxy.port || (this.secure ? 443 : 80)
};
if (this.secure) {
socket = tls.connect(info);
} else {
socket = net.connect(info);
}
fn(null, socket);
return socket;
};