http_client.go 803 B

12345678910111213141516171819202122232425262728293031323334
  1. package authority
  2. import (
  3. "crypto/tls"
  4. "crypto/x509"
  5. "fmt"
  6. "net/http"
  7. )
  8. // newHTTPClient will return an HTTP client that trusts the system cert pool and
  9. // the given roots, but only if the http.DefaultTransport is an *http.Transport.
  10. // If not, it will return the default HTTP client.
  11. func newHTTPClient(roots ...*x509.Certificate) (*http.Client, error) {
  12. if tr, ok := http.DefaultTransport.(*http.Transport); ok {
  13. pool, err := x509.SystemCertPool()
  14. if err != nil {
  15. return nil, fmt.Errorf("error initializing http client: %w", err)
  16. }
  17. for _, crt := range roots {
  18. pool.AddCert(crt)
  19. }
  20. tr = tr.Clone()
  21. tr.TLSClientConfig = &tls.Config{
  22. MinVersion: tls.VersionTLS12,
  23. RootCAs: pool,
  24. }
  25. return &http.Client{
  26. Transport: tr,
  27. }, nil
  28. }
  29. return &http.Client{}, nil
  30. }