From 2c7665792fe1e9969c10e9ef7d5c15693fc23272 Mon Sep 17 00:00:00 2001 From: Elethom Hunter Date: Thu, 20 Feb 2020 22:57:15 +0800 Subject: [PATCH] request: add proxy support --- lib/request.js | 14 +++++++++++++- package.json | 6 +++++- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/lib/request.js b/lib/request.js index 02c7aca..e253cc2 100644 --- a/lib/request.js +++ b/lib/request.js @@ -9,6 +9,8 @@ const assert = require('bsert'); const {Stream} = require('stream'); const mime = require('./mime'); +const tryRequire = require('try-require'); +const ProxyAgent = tryRequire('proxy-agent'); /* * Lazily Loaded @@ -50,6 +52,7 @@ class RequestOptions { this.timeout = 5000; this.buffer = buffer || false; this.headers = Object.create(null); + this.proxy = process.env.socks_proxy || process.env.all_proxy; // Hack ensureRequires(); @@ -185,6 +188,10 @@ class RequestOptions { this.lookup = options.lookup; } + if (options.proxy != null) { + assert(typeof options.proxy === 'string'); + } + return this; } @@ -270,6 +277,11 @@ class RequestOptions { return this.ssl ? https : http; } + getProxyAgent() { + if (typeof ProxyAgent !== undefined) + return new ProxyAgent(this.proxy); + } + getHeaders() { const headers = Object.create(null); @@ -330,7 +342,7 @@ class RequestOptions { port: this.port, path: this.path + query, headers: this.getHeaders(), - agent: this.pool ? null : false, + agent: this.pool ? null : this.proxy ? this.getProxyAgent() : false, lookup: this.lookup || undefined, rejectUnauthorized: this.strictSSL }; diff --git a/package.json b/package.json index 1ad51fa..d18eeb8 100644 --- a/package.json +++ b/package.json @@ -19,7 +19,8 @@ "test": "bmocha --reporter spec test/*-test.js" }, "dependencies": { - "bsert": "~0.0.10" + "bsert": "~0.0.10", + "try-require": "^1.2.1" }, "devDependencies": { "bmocha": "^2.1.0" @@ -29,5 +30,8 @@ }, "browser": { "./lib/request": "./lib/request-browser.js" + }, + "optionalDependencies": { + "proxy-agent": "^3.1.1" } }