Skip to content

Commit

Permalink
ghttp add SetDisableDNS
Browse files Browse the repository at this point in the history
  • Loading branch information
snail007 committed Feb 21, 2025
1 parent 4f15dae commit 3ca556e
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 9 deletions.
25 changes: 16 additions & 9 deletions util/http/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ type HTTPClient struct {
proxyUsed *url.URL
beforeDo []BeforeDoClientFunc
afterDo []AfterDoClientFunc
disableDNS bool
}

// NewHTTPClient new a HTTPClient, all request shared one http.Client object, keep cookies, keepalive etc.
Expand All @@ -117,6 +118,10 @@ func NewHTTPClient() *HTTPClient {
}
}

func (s *HTTPClient) SetDisableDNS(disableDNS bool) {
s.disableDNS = disableDNS
}

// SetBeforeDo sets callback call before request sent.
func (s *HTTPClient) SetBeforeDo(beforeDo BeforeDoClientFunc) *HTTPClient {
return s.setBeforeDo(beforeDo, true)
Expand Down Expand Up @@ -523,16 +528,18 @@ func (s *HTTPClient) newTransport(timeout time.Duration) (tr *http.Transport, er
}
conn, err = j.Dial(addr)
} else {
host, port, _ := net.SplitHostPort(addr)
iparr, e := resolver.LookupIPAddr(ctx, host)
if e != nil {
return nil, e
}
if len(iparr) == 0 {
return nil, fmt.Errorf("can not resolve domain %s", host)
if !s.disableDNS {
host, port, _ := net.SplitHostPort(addr)
iparr, e := resolver.LookupIPAddr(ctx, host)
if e != nil {
return nil, e
}
if len(iparr) == 0 {
return nil, fmt.Errorf("can not resolve domain %s", host)
}
ip := iparr[0]
addr = net.JoinHostPort(ip.String(), port)
}
ip := iparr[0]
addr = net.JoinHostPort(ip.String(), port)
if s.dialer != nil {
conn, err = s.dialer(network, addr, timeout)
} else {
Expand Down
1 change: 1 addition & 0 deletions util/http/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,7 @@ func TestHTTPClient_SetDNS(t *testing.T) {
assert2.Equal(t, "value1", jar.Cookies(u1)[0].Value)
assert := assert2.New(t)
client := NewHTTPClient()
client.SetDisableDNS(false)
client.SetDNS("114.114.114.114:53")
body1, _, _, _ := client.Get("http://www.baidu.com/", time.Second*5, nil, map[string]string{"token": "200"})
client.SetDNS("8.8.8.8:53")
Expand Down

0 comments on commit 3ca556e

Please sign in to comment.