DocsHTTPConfiguring the client

Configuring the client

Set the identity headers through Config, swap the underlying transport, and inject a logger.

NewClient takes a Config and a list of options. Config is the static, construction-time setup, mainly the base URL and the headers that identify the client on every request. The options cover the two things you swap out, the underlying transport and the logger.

Config and identity headers

Config seeds a set of client-wide headers used for tracing and client identification. Each maps to a documented header constant.

client := http.NewClient(http.Config{
	BaseURL:     "https://api.example.com",
	UserAgent:   "awee-cli/1.4.0",
	Platform:    "cli",
	AppVersion:  "1.4.0",
	ClientID:    "install-7f3a",
	ServiceName: "billing-worker",
})
Config fieldHeader sent
UserAgentUser-Agent
PlatformX-Client-Platform
AppVersionX-Client-Version
ClientIDX-Client-ID
ServiceNameX-Service-Name

An empty field sends no header. Anything you put in Config.Headers is also sent on every request, and a per-request header of the same name overrides it. The header names are exported as constants, listed in the headers reference.

Formatting a user agent

UserAgent builds a conventional user-agent string from the app name, version, and platform details, so you do not hand-format one.

ua := http.UserAgent("awee-cli", "1.4.0", runtime.GOOS, osVersion, runtime.GOARCH)
// "awee-cli/1.4.0 (darwin 14.5; arm64)"

client := http.NewClient(http.Config{UserAgent: ua})

Swap the transport

By default the client uses http.DefaultClient, which has no timeout. Pass WithHTTPClient to set your own timeout or transport, or to inject a stub in tests.

client := http.NewClient(cfg,
	http.WithHTTPClient(&http.Client{Timeout: 5 * time.Second}),
)

Here http.Client is the standard library's client. A nil client is ignored, so the default stays in place.

Inject a logger

The client is silent by default. Pass WithLogger to have it write request and response diagnostics.

client := http.NewClient(cfg, http.WithLogger(logger))

Logger is a minimal leveled interface with Trace, Debug, Info, Warn, and Error. It is satisfied structurally by github.com/toaweme/log, so you can pass that directly with no adapter. There is deliberately no With or handler method, so any leveled logger fits. See the helpers reference for the exact interface.