github.com/hashicorp/terraform-plugin-sdk@v1.17.2/internal/httpclient/client.go (about) 1 package httpclient 2 3 import ( 4 "fmt" 5 "log" 6 "net/http" 7 "os" 8 "strings" 9 10 cleanhttp "github.com/hashicorp/go-cleanhttp" 11 "github.com/hashicorp/terraform-plugin-sdk/internal/version" 12 ) 13 14 const uaEnvVar = "TF_APPEND_USER_AGENT" 15 const userAgentFormat = "Terraform/%s" 16 17 // New returns the DefaultPooledClient from the cleanhttp 18 // package that will also send a Terraform User-Agent string. 19 func New() *http.Client { 20 cli := cleanhttp.DefaultPooledClient() 21 cli.Transport = &userAgentRoundTripper{ 22 userAgent: UserAgentString(), 23 inner: cli.Transport, 24 } 25 return cli 26 } 27 28 type userAgentRoundTripper struct { 29 inner http.RoundTripper 30 userAgent string 31 } 32 33 func (rt *userAgentRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { 34 if _, ok := req.Header["User-Agent"]; !ok { 35 req.Header.Set("User-Agent", rt.userAgent) 36 } 37 log.Printf("[TRACE] HTTP client %s request to %s", req.Method, req.URL.String()) 38 return rt.inner.RoundTrip(req) 39 } 40 41 func UserAgentString() string { 42 ua := fmt.Sprintf(userAgentFormat, version.Version) 43 44 if add := os.Getenv(uaEnvVar); add != "" { 45 add = strings.TrimSpace(add) 46 if len(add) > 0 { 47 ua += " " + add 48 log.Printf("[DEBUG] Using modified User-Agent: %s", ua) 49 } 50 } 51 52 return ua 53 }