github.com/haraldrudell/parl@v0.4.176/pnet/httpclient.go (about) 1 /* 2 © 2021–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/) 3 ISC License 4 */ 5 6 package pnet 7 8 import ( 9 "context" 10 "crypto/tls" 11 "crypto/x509" 12 "net/http" 13 14 "github.com/haraldrudell/parl/perrors" 15 ) 16 17 type HttpClient struct { 18 http.Client 19 } 20 21 func Get(requestURL string, tlsConfig *tls.Config, ctx context.Context) (resp *http.Response, err error) { 22 return NewHttpClient(tlsConfig).Get(requestURL, ctx) 23 } 24 25 func NewTLSConfig(cert *x509.Certificate) (tlsConfig *tls.Config) { 26 certPool := x509.NewCertPool() 27 certPool.AddCert(cert) 28 return &tls.Config{RootCAs: certPool} 29 } 30 31 func NewHttpClient(tlsConfig *tls.Config) (httpClient *HttpClient) { 32 return &HttpClient{Client: http.Client{ 33 Transport: NewTransport(tlsConfig), 34 CheckRedirect: CheckRedirect, 35 Jar: nil, 36 Timeout: 0, 37 }} 38 } 39 40 func (ct *HttpClient) Get(requestURL string, ctx context.Context) (resp *http.Response, err error) { 41 if ctx == nil { 42 ctx = context.Background() 43 } 44 var httpRequest *http.Request 45 if httpRequest, err = http.NewRequestWithContext(ctx, "GET", requestURL, nil); err != nil { 46 panic(perrors.Errorf("http.NewRequestWithContext: '%w'", err)) 47 } 48 return ct.Client.Do(httpRequest) 49 } 50 51 func CheckRedirect(req *http.Request, via []*http.Request) (err error) { 52 return 53 } 54 55 func NewTransport(tlsConfig *tls.Config) (httpTransport *http.Transport) { 56 var defaultTransport *http.Transport 57 var ok bool 58 if defaultTransport, ok = http.DefaultTransport.(*http.Transport); !ok { 59 panic(perrors.New("DefaultTransport not http.Transport type")) 60 } 61 httpTransport = defaultTransport.Clone() 62 63 // ensure tlsConfig is used 64 httpTransport.TLSClientConfig = tlsConfig 65 httpTransport.DialTLSContext = nil 66 return 67 }