From 9b60efd5ccdd61b3a771cace1b1082fbf20e1978 Mon Sep 17 00:00:00 2001 From: bcoe Date: Thu, 5 Nov 2020 11:44:23 -0800 Subject: [PATCH] feat: add support for no_proxy environment variable Refs https://github.com/googleapis/gaxios/issues/69 --- src/gaxios.ts | 9 ++++++--- test/test.getch.ts | 30 ++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 3 deletions(-) diff --git a/src/gaxios.ts b/src/gaxios.ts index 969fbac4..6e7e715c 100644 --- a/src/gaxios.ts +++ b/src/gaxios.ts @@ -44,7 +44,11 @@ let HttpsProxyAgent: any; // Figure out if we should be using a proxy. Only if it's required, load // the https-proxy-agent module as it adds startup cost. -function loadProxy() { +function loadProxy(url: string) { + const noProxy = process.env.no_proxy ?? process.env.NO_PROXY; + if (noProxy && url === noProxy) { + return; + } const proxy = process.env.HTTPS_PROXY || process.env.https_proxy || @@ -55,7 +59,6 @@ function loadProxy() { } return proxy; } -loadProxy(); export class Gaxios { private agentCache = new Map< @@ -219,7 +222,7 @@ export class Gaxios { } opts.method = opts.method || 'GET'; - const proxy = loadProxy(); + const proxy = loadProxy(opts.url); if (proxy) { if (this.agentCache.has(proxy)) { opts.agent = this.agentCache.get(proxy); diff --git a/test/test.getch.ts b/test/test.getch.ts index a568529d..0a1cfc72 100644 --- a/test/test.getch.ts +++ b/test/test.getch.ts @@ -259,6 +259,36 @@ describe('🥁 configuration options', () => { assert.ok(res.config.agent instanceof HttpsProxyAgent); }); + describe('no_proxy', () => { + it('should not proxy when url matches no_proxy', async () => { + const url = 'https://example.com'; + sandbox.stub(process, 'env').value({ + https_proxy: 'https://fake.proxy', + no_proxy: 'https://example.com', + }); + const body = {hello: '🌎'}; + const scope = nock(url).get('/').reply(200, body); + const res = await request({url}); + scope.done(); + assert.deepStrictEqual(res.data, body); + assert.strictEqual(res.config.agent, undefined); + }); + + it('should still proxy if url does not match no_proxy', async () => { + const url = 'https://example2.com'; + sandbox.stub(process, 'env').value({ + https_proxy: 'https://fake.proxy', + no_proxy: 'https://example.com', + }); + const body = {hello: '🌎'}; + const scope = nock(url).get('/').reply(200, body); + const res = await request({url}); + scope.done(); + assert.deepStrictEqual(res.data, body); + assert.ok(res.config.agent instanceof HttpsProxyAgent); + }); + }); + it('should load the proxy from the cache', async () => { sandbox.stub(process, 'env').value({HTTPS_PROXY: 'https://fake.proxy'}); const body = {hello: '🌎'};