From 77bf949027cf471deb232808ca25bdcef7146273 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=A8=E5=B4=9F?= Date: Wed, 3 Apr 2024 14:56:09 +0800 Subject: [PATCH] fix(netutil): Add proxy ip to send request --- netutil/http.go | 6 ++++++ netutil/http_test.go | 20 ++++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/netutil/http.go b/netutil/http.go index 54ad55e9..5d1d2289 100644 --- a/netutil/http.go +++ b/netutil/http.go @@ -109,6 +109,7 @@ type HttpClientConfig struct { HandshakeTimeout time.Duration ResponseTimeout time.Duration Verbose bool + Proxy *url.URL } // defaultHttpClientConfig defalut client config. @@ -164,6 +165,11 @@ func NewHttpClientWithConfig(config *HttpClientConfig) *HttpClient { client.TLS = config.TLSConfig } + if config.Proxy != nil { + transport := client.Client.Transport.(*http.Transport) + transport.Proxy = http.ProxyURL(config.Proxy) + } + return client } diff --git a/netutil/http_test.go b/netutil/http_test.go index 947e4f50..8ec54034 100644 --- a/netutil/http_test.go +++ b/netutil/http_test.go @@ -11,6 +11,7 @@ import ( "net/url" "os" "testing" + "time" "github.com/duke-git/lancet/v2/internal" ) @@ -361,3 +362,22 @@ func TestSendRequestWithFilePath(t *testing.T) { t.Fatalf("expected %d, got %d", http.StatusOK, resp.StatusCode) } } + +func TestProxy(t *testing.T) { + config := &HttpClientConfig{ + HandshakeTimeout: 20 * time.Second, + ResponseTimeout: 40 * time.Second, + Proxy: &url.URL{ + Scheme: "http", + Host: "46.17.63.166:18888", + }, + } + httpClient := NewHttpClientWithConfig(config) + resp, err := httpClient.Get("https://www.ipplus360.com/getLocation") + if err != nil { + t.Fatal(err) + } + if resp.StatusCode != http.StatusOK { + t.Fatalf("expected %d, got %d", http.StatusOK, resp.StatusCode) + } +}