fix: set proxy for http module, close #2647 #2094

This commit is contained in:
DIYgod
2019-08-03 20:38:37 +08:00
parent ddd7a871fd
commit 08878e1d52
3 changed files with 84 additions and 53 deletions

View File

@@ -1,52 +1,8 @@
const logger = require('./logger');
const config = require('@/config');
const SocksProxyAgent = require('socks-proxy-agent');
const tunnel = require('tunnel');
const got = require('got');
const queryString = require('query-string');
let agent = null;
if (config.proxy && config.proxy.protocol && config.proxy.host && config.proxy.port) {
agent = {};
const proxyUrl = `${config.proxy.protocol}://${config.proxy.host}:${config.proxy.port}`;
switch (config.proxy.protocol) {
case 'socks':
agent.http = new SocksProxyAgent(proxyUrl);
agent.https = new SocksProxyAgent(proxyUrl);
break;
case 'http':
process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0;
agent.http = tunnel.httpOverHttp({
proxy: {
host: config.proxy.host,
port: parseInt(config.proxy.port),
},
});
agent.https = tunnel.httpsOverHttp({
proxy: {
host: config.proxy.host,
port: parseInt(config.proxy.port),
},
});
break;
case 'https':
agent.http = tunnel.httpOverHttps({
proxy: {
host: config.proxy.host,
port: parseInt(config.proxy.port),
},
});
agent.https = tunnel.httpsOverHttps({
proxy: {
host: config.proxy.host,
port: parseInt(config.proxy.port),
},
});
break;
}
}
const custom = got.extend({
retry: {
retries: config.requestRetry,
@@ -82,15 +38,6 @@ const custom = got.extend({
options.query = options.query || queryString.stringify(options.params);
options.searchParams = options.query; // for Got v11 after
}
if (agent && new RegExp(config.proxy.url_regex).test(options.href)) {
options.agent = agent[options.protocol.slice(0, -1)];
if (config.proxy.auth) {
options.headers['Proxy-Authorization'] = `Basic ${config.proxy.auth}`;
}
logger.info(`Proxy for ${options.href}`);
}
},
],
},