transport_template_provider.go raw

   1  // Copyright (c) 2016, 2018, 2025, Oracle and/or its affiliates.  All rights reserved.
   2  // This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
   3  
   4  package common
   5  
   6  import (
   7  	"crypto/tls"
   8  	"net"
   9  	"net/http"
  10  	"time"
  11  )
  12  
  13  // TransportTemplateProvider defines a function that creates a new http transport
  14  // from a given TLS client config.
  15  type TransportTemplateProvider func(tlsClientConfig *tls.Config) (http.RoundTripper, error)
  16  
  17  // NewOrDefault creates a new TransportTemplate
  18  // If t is nil, then DefaultTransport is returned
  19  func (t TransportTemplateProvider) NewOrDefault(tlsClientConfig *tls.Config) (http.RoundTripper, error) {
  20  	if t == nil {
  21  		return DefaultTransport(tlsClientConfig)
  22  	}
  23  	return t(tlsClientConfig)
  24  }
  25  
  26  // DefaultTransport creates a clone of http.DefaultTransport
  27  // and applies the tlsClientConfig on top of it.
  28  // The result is never nil, to prevent panics in client code.
  29  // Never returns any errors, but needs to return an error
  30  // to adhere to TransportTemplate interface.
  31  func DefaultTransport(tlsClientConfig *tls.Config) (*http.Transport, error) {
  32  	transport := CloneHTTPDefaultTransport()
  33  	if isExpectHeaderDisabled := IsEnvVarFalse(UsingExpectHeaderEnvVar); !isExpectHeaderDisabled {
  34  		transport.Proxy = http.ProxyFromEnvironment
  35  		transport.DialContext = (&net.Dialer{
  36  			Timeout:   30 * time.Second,
  37  			KeepAlive: 30 * time.Second,
  38  			DualStack: true,
  39  		}).DialContext
  40  		transport.ForceAttemptHTTP2 = true
  41  		transport.MaxIdleConns = 100
  42  		transport.IdleConnTimeout = 90 * time.Second
  43  		transport.TLSHandshakeTimeout = 10 * time.Second
  44  		transport.ExpectContinueTimeout = 3 * time.Second
  45  	}
  46  	transport.TLSClientConfig = tlsClientConfig
  47  	return transport, nil
  48  }
  49  
  50  // CloneHTTPDefaultTransport returns a clone of http.DefaultTransport.
  51  func CloneHTTPDefaultTransport() *http.Transport {
  52  	return http.DefaultTransport.(*http.Transport).Clone()
  53  }
  54