NewHTTPClient returns a new HTTPClient
(opt *HTTPOptions, logger *Logger)
| 46 | |
| 47 | // NewHTTPClient returns a new HTTPClient |
| 48 | func NewHTTPClient(opt *HTTPOptions, logger *Logger) (*HTTPClient, error) { |
| 49 | var proxyURLFunc func(*http.Request) (*url.URL, error) |
| 50 | var client HTTPClient |
| 51 | proxyURLFunc = http.ProxyFromEnvironment |
| 52 | |
| 53 | if opt == nil { |
| 54 | return nil, errors.New("options is nil") |
| 55 | } |
| 56 | |
| 57 | if opt.Proxy != "" { |
| 58 | proxyURL, err := url.Parse(opt.Proxy) |
| 59 | if err != nil { |
| 60 | return nil, fmt.Errorf("proxy URL is invalid (%w)", err) |
| 61 | } |
| 62 | proxyURLFunc = http.ProxyURL(proxyURL) |
| 63 | } |
| 64 | |
| 65 | var redirectFunc func(req *http.Request, via []*http.Request) error |
| 66 | if !opt.FollowRedirect { |
| 67 | redirectFunc = func(_ *http.Request, _ []*http.Request) error { |
| 68 | return http.ErrUseLastResponse |
| 69 | } |
| 70 | } else { |
| 71 | redirectFunc = nil |
| 72 | } |
| 73 | |
| 74 | tlsConfig := tls.Config{ |
| 75 | InsecureSkipVerify: opt.NoTLSValidation, // nolint:gosec |
| 76 | // enable TLS1.0 and TLS1.1 support |
| 77 | MinVersion: tls.VersionTLS10, |
| 78 | } |
| 79 | if opt.TLSCertificate != nil { |
| 80 | tlsConfig.Certificates = []tls.Certificate{*opt.TLSCertificate} |
| 81 | } |
| 82 | if opt.TLSRenegotiation { |
| 83 | tlsConfig.Renegotiation = tls.RenegotiateOnceAsClient |
| 84 | } |
| 85 | |
| 86 | transport := &http.Transport{ |
| 87 | Proxy: proxyURLFunc, |
| 88 | MaxIdleConns: 100, |
| 89 | MaxIdleConnsPerHost: 100, |
| 90 | TLSClientConfig: &tlsConfig, |
| 91 | } |
| 92 | |
| 93 | // set specific network interface |
| 94 | if opt.LocalAddr != nil { |
| 95 | logger.Debugf("Setting local address to %s", opt.LocalAddr.String()) |
| 96 | dialer := &net.Dialer{ |
| 97 | Timeout: opt.Timeout, |
| 98 | LocalAddr: opt.LocalAddr, |
| 99 | } |
| 100 | transport.DialContext = dialer.DialContext |
| 101 | } |
| 102 | |
| 103 | client.client = &http.Client{ |
| 104 | Timeout: opt.Timeout, |
| 105 | CheckRedirect: redirectFunc, |