Allow callers to append to user agent

This commit is contained in:
Paul Tyng 2018-03-15 09:25:57 -04:00
parent fb9531b3d9
commit 6284f99708
No known key found for this signature in database
GPG Key ID: E518875D6C65835A
2 changed files with 62 additions and 1 deletions

View File

@ -2,15 +2,29 @@ package httpclient
import (
"fmt"
"log"
"net/http"
"os"
"strings"
"github.com/hashicorp/terraform/version"
)
const userAgentFormat = "Terraform/%s"
const uaEnvVar = "TF_APPEND_USER_AGENT"
func UserAgentString() string {
return fmt.Sprintf(userAgentFormat, version.Version)
ua := fmt.Sprintf(userAgentFormat, version.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
}
type userAgentRoundTripper struct {

View File

@ -0,0 +1,47 @@
package httpclient
import (
"fmt"
"os"
"testing"
"github.com/hashicorp/terraform/version"
)
func TestUserAgentString_env(t *testing.T) {
expectedBase := fmt.Sprintf(userAgentFormat, version.Version)
if oldenv, isSet := os.LookupEnv(uaEnvVar); isSet {
defer os.Setenv(uaEnvVar, oldenv)
} else {
defer os.Unsetenv(uaEnvVar)
}
for i, c := range []struct {
expected string
additional string
}{
{expectedBase, ""},
{expectedBase, " "},
{expectedBase, " \n"},
{fmt.Sprintf("%s test/1", expectedBase), "test/1"},
{fmt.Sprintf("%s test/2", expectedBase), "test/2 "},
{fmt.Sprintf("%s test/3", expectedBase), " test/3 "},
{fmt.Sprintf("%s test/4", expectedBase), "test/4 \n"},
} {
t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
if c.additional == "" {
os.Unsetenv(uaEnvVar)
} else {
os.Setenv(uaEnvVar, c.additional)
}
actual := UserAgentString()
if c.expected != actual {
t.Fatalf("Expected User-Agent '%s' does not match '%s'", c.expected, actual)
}
})
}
}