github.com/sandwich-go/boost@v1.3.29/httputil/default.go (about) 1 package httputil 2 3 import ( 4 "crypto/tls" 5 "github.com/sandwich-go/boost/httputil/dns" 6 "io" 7 "net/http" 8 "time" 9 ) 10 11 var ( 12 globalClient httpClient 13 defaultHTTPTimeout = time.Duration(10) * time.Second 14 defaultDNSCacheTime = time.Minute 15 ) 16 17 // SetDefaultHTTPClient 设置默认的 HTTP Client 18 func SetDefaultHTTPClient(c *http.Client) { globalClient.Client = c } 19 20 // SetDefaultTimeout 设置默认的超时时间 21 func SetDefaultTimeout(timeout time.Duration) { globalClient.Client.Timeout = timeout } 22 23 // Post 使用默认的 Client 发送 POST 请求 24 func Post(url, contentType string, body io.Reader) (resp *http.Response, err error) { 25 return globalClient.Post(url, contentType, body) 26 } 27 28 // Get 使用默认的 Client 发送 GET 请求 29 func Get(url string) (*http.Response, error) { 30 return globalClient.Get(url) 31 } 32 33 // Bytes 使用默认的 Client 发送 GET 请求,返回 bytes 数据 34 func Bytes(url string) ([]byte, error) { 35 return globalClient.Bytes(url) 36 } 37 38 // String 使用默认的 Client 发送 GET 请求,返回 string 数据 39 func String(url string) (string, error) { 40 return globalClient.String(url) 41 } 42 43 // JSON 使用默认的 Client 发送 GET 请求,返回 JSON 数据 44 func JSON(url string, v interface{}) error { 45 return globalClient.JSON(url, v) 46 } 47 48 func init() { 49 dc := dns.NewCache(dns.WithTTL(defaultDNSCacheTime)) 50 client := &http.Client{ 51 Timeout: defaultHTTPTimeout, 52 Transport: &http.Transport{ 53 DialContext: dc.GetDialContext(), 54 MaxIdleConns: 50, 55 IdleConnTimeout: 60 * time.Second, 56 TLSHandshakeTimeout: 5 * time.Second, 57 ExpectContinueTimeout: 1 * time.Second, 58 MaxResponseHeaderBytes: 5 * 1024, 59 TLSClientConfig: &tls.Config{ 60 InsecureSkipVerify: true, // 单向验证 61 }, 62 }, 63 } 64 SetDefaultHTTPClient(client) 65 }