From 6a93e7803868ecae22cee3699dd4a979a1fe7fbb Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Tue, 13 Jan 2026 14:45:25 +0100 Subject: [PATCH] cli/command: add WithAPIClientOptions option This option allows setting custom options to use when constructing the API client. Signed-off-by: Sebastiaan van Stijn --- cli/command/cli_options.go | 10 ++++++++++ cli/command/cli_test.go | 23 +++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/cli/command/cli_options.go b/cli/command/cli_options.go index 8df4ae6b4f1d..469932f9c399 100644 --- a/cli/command/cli_options.go +++ b/cli/command/cli_options.go @@ -104,6 +104,16 @@ func WithInitializeClient(makeClient func(*DockerCli) (client.APIClient, error)) } } +// WithAPIClientOptions configures additional [client.Opt] to use when +// initializing the API client. These options have no effect if a custom +// client is set (through [WithAPIClient] or [WithInitializeClient]). +func WithAPIClientOptions(c ...client.Opt) CLIOption { + return func(cli *DockerCli) error { + cli.clientOpts = append(cli.clientOpts, c...) + return nil + } +} + // envOverrideHTTPHeaders is the name of the environment-variable that can be // used to set custom HTTP headers to be sent by the client. This environment // variable is the equivalent to the HttpHeaders field in the configuration diff --git a/cli/command/cli_test.go b/cli/command/cli_test.go index be8ff2a66172..944cdfd2a100 100644 --- a/cli/command/cli_test.go +++ b/cli/command/cli_test.go @@ -393,3 +393,26 @@ func TestNewDockerCliWithCustomUserAgent(t *testing.T) { assert.NilError(t, err) assert.DeepEqual(t, received, "fake-agent/0.0.1") } + +func TestNewDockerCliWithAPIClientOptions(t *testing.T) { + var received string + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + received = r.UserAgent() + w.WriteHeader(http.StatusOK) + })) + defer ts.Close() + host := strings.Replace(ts.URL, "http://", "tcp://", 1) + opts := &flags.ClientOptions{Hosts: []string{host}} + + cli, err := NewDockerCli( + WithAPIClientOptions(client.WithUserAgent("fake-agent/0.0.1")), + ) + assert.NilError(t, err) + cli.currentContext = DefaultContextName + cli.options = opts + cli.configFile = &configfile.ConfigFile{} + + _, err = cli.Client().Ping(t.Context(), client.PingOptions{}) + assert.NilError(t, err) + assert.DeepEqual(t, received, "fake-agent/0.0.1") +}