@@ -18,8 +18,11 @@ package httputils
1818
1919import (
2020 "bytes"
21+ "crypto/tls"
22+ "crypto/x509"
2123 "encoding/json"
2224 "fmt"
25+ "io/ioutil"
2326 "net"
2427 "net/http"
2528 "reflect"
@@ -210,16 +213,37 @@ func Do(url string, headers map[string]string, timeout time.Duration) (string, e
210213
211214// HTTPGet sends an HTTP GET request with headers.
212215func HTTPGet (url string , headers map [string ]string ) (* http.Response , error ) {
213- return HTTPWithHeaders ("GET" , url , headers , 0 )
216+ return HTTPWithHeaders ("GET" , url , headers , 0 , nil )
214217}
215218
216219// HTTPGetTimeout sends an HTTP GET request with timeout.
217220func HTTPGetTimeout (url string , headers map [string ]string , timeout time.Duration ) (* http.Response , error ) {
218- return HTTPWithHeaders ("GET" , url , headers , timeout )
221+ return HTTPWithHeaders ("GET" , url , headers , timeout , nil )
222+ }
223+
224+ // HTTPGetWithTLS sends an HTTP GET request with TLS config.
225+ func HTTPGetWithTLS (url string , headers map [string ]string , timeout time.Duration , cacerts []string , insecure bool ) (* http.Response , error ) {
226+ roots := x509 .NewCertPool ()
227+ appendSuccess := false
228+ for _ , certPath := range cacerts {
229+ certBytes , err := ioutil .ReadFile (certPath )
230+ if err != nil {
231+ return nil , err
232+ }
233+ appendSuccess = appendSuccess || roots .AppendCertsFromPEM (certBytes )
234+ }
235+
236+ tlsConfig := & tls.Config {
237+ InsecureSkipVerify : insecure ,
238+ }
239+ if appendSuccess {
240+ tlsConfig .RootCAs = roots
241+ }
242+ return HTTPWithHeaders ("GET" , url , headers , timeout , tlsConfig )
219243}
220244
221245// HTTPWithHeaders sends an HTTP request with headers and specified method.
222- func HTTPWithHeaders (method , url string , headers map [string ]string , timeout time.Duration ) (* http.Response , error ) {
246+ func HTTPWithHeaders (method , url string , headers map [string ]string , timeout time.Duration , tlsConfig * tls. Config ) (* http.Response , error ) {
223247 req , err := http .NewRequest (method , url , nil )
224248 if err != nil {
225249 return nil , err
@@ -229,7 +253,16 @@ func HTTPWithHeaders(method, url string, headers map[string]string, timeout time
229253 req .Header .Add (k , v )
230254 }
231255
232- c := & http.Client {}
256+ var transport http.RoundTripper
257+ if tlsConfig != nil {
258+ transport = & http.Transport {
259+ TLSClientConfig : tlsConfig ,
260+ }
261+ }
262+
263+ c := & http.Client {
264+ Transport : transport ,
265+ }
233266 if timeout > 0 {
234267 c .Timeout = timeout
235268 }
0 commit comments