From fda38bb5647cd578a94d643c52168cb0858d2437 Mon Sep 17 00:00:00 2001 From: Murad Biashimov Date: Fri, 17 May 2024 13:01:54 +0200 Subject: [PATCH] refactor: cache user agent (#64) --- client.go | 16 ++++++++-------- client_test.go | 3 ++- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/client.go b/client.go index b73e6b3..d199bff 100644 --- a/client.go +++ b/client.go @@ -55,6 +55,13 @@ func NewClient(opts ...Option) (Client, error) { // Removes trailing / so it is easier later Host + URL d.Host = strings.TrimSuffix(d.Host, "/") + // Formats the user agent + d.UserAgent = fmt.Sprintf( + "go-client-codegen/%s %s", + strings.TrimLeft(Version(), "v"), + strings.TrimSpace(d.UserAgent), + ) + return newClient(d), nil } @@ -133,14 +140,7 @@ func (d *aivenClient) do(ctx context.Context, method, path string, v any) (*http } req.Header.Set("Content-Type", "application/json") - req.Header.Set( - "User-Agent", - strings.TrimSpace(fmt.Sprintf( - "go-client-codegen/%s %s", - strings.TrimLeft(Version(), "v"), - d.UserAgent, - )), - ) + req.Header.Set("User-Agent", d.UserAgent) req.Header.Set("Authorization", "aivenv1 "+d.Token) // TODO: BAD hack to get around pagination in most cases diff --git a/client_test.go b/client_test.go index 963741b..9b6792f 100644 --- a/client_test.go +++ b/client_test.go @@ -51,6 +51,7 @@ func TestServiceCreate(t *testing.T) { assert.NoError(t, err) assert.Equal(t, "foo", expectIn.ServiceName) assert.Equal(t, "kafka", expectIn.ServiceType) + assert.Regexp(t, `go-client-codegen/[0-9\.]+ unit-test`, r.Header["User-Agent"]) // Creates response w.Header().Set("Content-Type", "application/json") @@ -61,7 +62,7 @@ func TestServiceCreate(t *testing.T) { defer server.Close() // Points a new client to the server url - c, err := NewClient(TokenOpt("token"), HostOpt(server.URL)) + c, err := NewClient(TokenOpt("token"), HostOpt(server.URL), UserAgentOpt("unit-test")) require.NotNil(t, c) require.NoError(t, err)