diff --git a/client/client.go b/client/client.go index 46832d8a44..97dbbf70b9 100644 --- a/client/client.go +++ b/client/client.go @@ -304,8 +304,7 @@ func (cli *Client) getAPIPath(ctx context.Context, p string, query url.Values) s var apiPath string _ = cli.checkVersion(ctx) if cli.version != "" { - v := strings.TrimPrefix(cli.version, "v") - apiPath = path.Join(cli.basePath, "/v"+v, p) + apiPath = path.Join(cli.basePath, "/v"+strings.TrimPrefix(cli.version, "v"), p) } else { apiPath = path.Join(cli.basePath, p) } diff --git a/client/client_test.go b/client/client_test.go index 4322ff0c84..e1712010b0 100644 --- a/client/client_test.go +++ b/client/client_test.go @@ -420,6 +420,58 @@ func TestNegotiateAPIVersionWithFixedVersion(t *testing.T) { assert.Equal(t, client.ClientVersion(), customVersion) } +// TestCustomAPIVersion tests initializing the client with a custom +// version. +func TestCustomAPIVersion(t *testing.T) { + tests := []struct { + version string + expected string + }{ + { + version: "", + expected: api.DefaultVersion, + }, + { + version: "1.0", + expected: "1.0", + }, + { + version: "9.99", + expected: "9.99", + }, + { + version: "v", + expected: api.DefaultVersion, + }, + { + version: "v1.0", + expected: "1.0", + }, + { + version: "v9.99", + expected: "9.99", + }, + { + // When manually setting a version, no validation happens. + // so anything is accepted. + version: "something-weird", + expected: "something-weird", + }, + } + for _, tc := range tests { + t.Run(tc.version, func(t *testing.T) { + client, err := NewClientWithOpts(WithVersion(tc.version)) + assert.NilError(t, err) + assert.Equal(t, client.ClientVersion(), tc.expected) + + t.Setenv(EnvOverrideAPIVersion, tc.expected) + client, err = NewClientWithOpts(WithVersionFromEnv()) + assert.NilError(t, err) + assert.Equal(t, client.ClientVersion(), tc.expected) + }) + } +} + type roundTripFunc func(*http.Request) (*http.Response, error) func (rtf roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) { diff --git a/client/options.go b/client/options.go index ddb0ca3991..85b12447d5 100644 --- a/client/options.go +++ b/client/options.go @@ -6,6 +6,7 @@ import ( "net/http" "os" "path/filepath" + "strings" "time" "github.com/docker/go-connections/sockets" @@ -194,8 +195,8 @@ func WithTLSClientConfigFromEnv() Opt { // (see [WithAPIVersionNegotiation]). func WithVersion(version string) Opt { return func(c *Client) error { - if version != "" { - c.version = version + if v := strings.TrimPrefix(version, "v"); v != "" { + c.version = v c.manualOverride = true } return nil