Skip to content

Commit

Permalink
fix(netutil): Add proxy ip to send request
Browse files Browse the repository at this point in the history
  • Loading branch information
杨崟 committed Apr 3, 2024
1 parent aa74400 commit 77bf949
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
6 changes: 6 additions & 0 deletions netutil/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ type HttpClientConfig struct {
HandshakeTimeout time.Duration
ResponseTimeout time.Duration
Verbose bool
Proxy *url.URL
}

// defaultHttpClientConfig defalut client config.
Expand Down Expand Up @@ -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
}

Expand Down
20 changes: 20 additions & 0 deletions netutil/http_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"net/url"
"os"
"testing"
"time"

"github.com/duke-git/lancet/v2/internal"
)
Expand Down Expand Up @@ -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)
}
}

0 comments on commit 77bf949

Please sign in to comment.