Merge pull request #22272 from hashicorp/f-httpclient-ua
httpclient: Introduce composable UserAgent()
This commit is contained in:
commit
98a796c3a3
|
@ -13,6 +13,7 @@ import (
|
|||
const userAgentFormat = "Terraform/%s"
|
||||
const uaEnvVar = "TF_APPEND_USER_AGENT"
|
||||
|
||||
// Deprecated: Use UserAgent(version) instead
|
||||
func UserAgentString() string {
|
||||
ua := fmt.Sprintf(userAgentFormat, version.Version)
|
||||
|
||||
|
@ -39,3 +40,17 @@ func (rt *userAgentRoundTripper) RoundTrip(req *http.Request) (*http.Response, e
|
|||
log.Printf("[TRACE] HTTP client %s request to %s", req.Method, req.URL.String())
|
||||
return rt.inner.RoundTrip(req)
|
||||
}
|
||||
|
||||
func TerraformUserAgent(version string) string {
|
||||
ua := fmt.Sprintf("HashiCorp Terraform/%s (+https://www.terraform.io)", version)
|
||||
|
||||
if add := os.Getenv(uaEnvVar); add != "" {
|
||||
add = strings.TrimSpace(add)
|
||||
if len(add) > 0 {
|
||||
ua += " " + add
|
||||
log.Printf("[DEBUG] Using modified User-Agent: %s", ua)
|
||||
}
|
||||
}
|
||||
|
||||
return ua
|
||||
}
|
||||
|
|
|
@ -43,5 +43,36 @@ func TestUserAgentString_env(t *testing.T) {
|
|||
}
|
||||
})
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestUserAgentAppendViaEnvVar(t *testing.T) {
|
||||
if oldenv, isSet := os.LookupEnv(uaEnvVar); isSet {
|
||||
defer os.Setenv(uaEnvVar, oldenv)
|
||||
} else {
|
||||
defer os.Unsetenv(uaEnvVar)
|
||||
}
|
||||
|
||||
expectedBase := "HashiCorp Terraform/0.0.0 (+https://www.terraform.io)"
|
||||
|
||||
testCases := []struct {
|
||||
envVarValue string
|
||||
expected string
|
||||
}{
|
||||
{"", expectedBase},
|
||||
{" ", expectedBase},
|
||||
{" \n", expectedBase},
|
||||
{"test/1", expectedBase + " test/1"},
|
||||
{"test/1 (comment)", expectedBase + " test/1 (comment)"},
|
||||
}
|
||||
|
||||
for i, tc := range testCases {
|
||||
t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
|
||||
os.Unsetenv(uaEnvVar)
|
||||
os.Setenv(uaEnvVar, tc.envVarValue)
|
||||
givenUA := TerraformUserAgent("0.0.0")
|
||||
if givenUA != tc.expected {
|
||||
t.Fatalf("Expected User-Agent '%s' does not match '%s'", tc.expected, givenUA)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
@ -6,8 +6,7 @@ import (
|
|||
|
||||
// Generate a UserAgent string
|
||||
//
|
||||
// Deprecated: Use httpclient.UserAgentString if you are setting your
|
||||
// own User-Agent header.
|
||||
// Deprecated: Use httpclient.UserAgent(version) instead
|
||||
func UserAgentString() string {
|
||||
return httpclient.UserAgentString()
|
||||
}
|
||||
|
|
|
@ -4,7 +4,7 @@ import (
|
|||
"github.com/hashicorp/terraform/version"
|
||||
)
|
||||
|
||||
// TODO: update providers to use the version package directly
|
||||
// Deprecated: Providers should use schema.Provider.TerraformVersion instead
|
||||
func VersionString() string {
|
||||
return version.String()
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue