Skip to content

Commit 6a93e78

Browse files
committed
cli/command: add WithAPIClientOptions option
This option allows setting custom options to use when constructing the API client. Signed-off-by: Sebastiaan van Stijn <[email protected]>
1 parent 07d7ef1 commit 6a93e78

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

cli/command/cli_options.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,16 @@ func WithInitializeClient(makeClient func(*DockerCli) (client.APIClient, error))
104104
}
105105
}
106106

107+
// WithAPIClientOptions configures additional [client.Opt] to use when
108+
// initializing the API client. These options have no effect if a custom
109+
// client is set (through [WithAPIClient] or [WithInitializeClient]).
110+
func WithAPIClientOptions(c ...client.Opt) CLIOption {
111+
return func(cli *DockerCli) error {
112+
cli.clientOpts = append(cli.clientOpts, c...)
113+
return nil
114+
}
115+
}
116+
107117
// envOverrideHTTPHeaders is the name of the environment-variable that can be
108118
// used to set custom HTTP headers to be sent by the client. This environment
109119
// variable is the equivalent to the HttpHeaders field in the configuration

cli/command/cli_test.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -393,3 +393,26 @@ func TestNewDockerCliWithCustomUserAgent(t *testing.T) {
393393
assert.NilError(t, err)
394394
assert.DeepEqual(t, received, "fake-agent/0.0.1")
395395
}
396+
397+
func TestNewDockerCliWithAPIClientOptions(t *testing.T) {
398+
var received string
399+
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
400+
received = r.UserAgent()
401+
w.WriteHeader(http.StatusOK)
402+
}))
403+
defer ts.Close()
404+
host := strings.Replace(ts.URL, "http://", "tcp://", 1)
405+
opts := &flags.ClientOptions{Hosts: []string{host}}
406+
407+
cli, err := NewDockerCli(
408+
WithAPIClientOptions(client.WithUserAgent("fake-agent/0.0.1")),
409+
)
410+
assert.NilError(t, err)
411+
cli.currentContext = DefaultContextName
412+
cli.options = opts
413+
cli.configFile = &configfile.ConfigFile{}
414+
415+
_, err = cli.Client().Ping(t.Context(), client.PingOptions{})
416+
assert.NilError(t, err)
417+
assert.DeepEqual(t, received, "fake-agent/0.0.1")
418+
}

0 commit comments

Comments
 (0)