From 67656c54e1a18de56829a44b2d036c5f726735b5 Mon Sep 17 00:00:00 2001 From: ddo Date: Thu, 1 Aug 2019 15:16:52 +0000 Subject: [PATCH] add client#UnSetProxy --- client/transport.go | 24 ++++++++++++++++++++++++ client/transport_test.go | 36 ++++++++++++++++++++++++++++++------ 2 files changed, 54 insertions(+), 6 deletions(-) diff --git a/client/transport.go b/client/transport.go index 75135db..4decd28 100644 --- a/client/transport.go +++ b/client/transport.go @@ -9,9 +9,15 @@ import ( ) // SetProxy sets client proxy by url string +// if url is empty, no proxy is used func (c *Client) SetProxy(rawURL string) (err error) { log.Info("url:", rawURL) + if rawURL == "" { + c.UnSetProxy() + return + } + u, err := url.Parse(rawURL) if err != nil { log.Error(err) @@ -48,3 +54,21 @@ func (c *Client) SetProxy(rawURL string) (err error) { log.Info("DONE:", u) return } + +// UnSetProxy unsets client proxy +func (c *Client) UnSetProxy() { + log.Info() + + client := c.httpClient + if client.Transport == nil { + return + } + + transport, ok := client.Transport.(*http.Transport) + if !ok { + return + } + + transport.Proxy = nil + return +} diff --git a/client/transport_test.go b/client/transport_test.go index c1d281a..b461bea 100644 --- a/client/transport_test.go +++ b/client/transport_test.go @@ -5,6 +5,10 @@ import ( "testing" ) +const ( + test_proxy_url = "https://127.0.0.1:8888" +) + func TestSetProxy(t *testing.T) { client := New(nil) if client == nil { @@ -12,18 +16,19 @@ func TestSetProxy(t *testing.T) { return } - err := client.SetProxy("https://127.0.0.1:8888") + err := client.SetProxy(test_proxy_url) if err != nil { t.Error() return } - proxy, err := client.httpClient.Transport.(*http.Transport).Proxy(nil) + transport := client.httpClient.Transport.(*http.Transport) + proxy, err := transport.Proxy(nil) if err != nil { t.Error() return } - if proxy.String() != "https://127.0.0.1:8888" { + if proxy.String() != test_proxy_url { t.Error() return } @@ -45,19 +50,38 @@ func TestSetProxyInvalidURL(t *testing.T) { func TestSetProxyFromNew(t *testing.T) { client := New(&Option{ - Proxy: "https://127.0.0.1:8888", + Proxy: test_proxy_url, }) if client == nil { t.Error() return } - proxy, err := client.httpClient.Transport.(*http.Transport).Proxy(nil) + transport := client.httpClient.Transport.(*http.Transport) + proxy, err := transport.Proxy(nil) if err != nil { t.Error() return } - if proxy.String() != "https://127.0.0.1:8888" { + if proxy.String() != test_proxy_url { + t.Error() + return + } +} + +func TestUnSetProxy(t *testing.T) { + client := New(&Option{ + Proxy: test_proxy_url, + }) + if client == nil { + t.Error() + return + } + + client.UnSetProxy() + + transport := client.httpClient.Transport.(*http.Transport) + if transport.Proxy != nil { t.Error() return }