Functional Options For Client Config

Variadic Option closures applied over defaults make client constructors extensible: callers override only the knobs they care about.

GoConfig Management

Code

gosnippet
43 lines
package main

import (
	"fmt"
	"time"
)

type Client struct {
	baseURL string
	timeout time.Duration
	retries int
}

// Option 持有对 Client 的闭包:构造时逐个应用
type Option func(*Client)

func WithTimeout(d time.Duration) Option {
	return func(c *Client) { c.timeout = d }
}

func WithRetries(n int) Option {
	return func(c *Client) { c.retries = n }
}

// NewClient 先给生产可用的默认值,再让 Option 按调用方意图覆盖
func NewClient(baseURL string, opts ...Option) *Client {
	c := &Client{baseURL: baseURL, timeout: 5 * time.Second, retries: 1}
	for _, opt := range opts {
		opt(c)
	}
	return c
}

func (c *Client) String() string {
	return fmt.Sprintf("%s timeout=%s retries=%d", c.baseURL, c.timeout, c.retries)
}

func main() {
	fmt.Println("default:", NewClient("https://api.example.com"))
	fmt.Println("custom:", NewClient("https://api.example.com",
		WithTimeout(2*time.Second),
		WithRetries(5)))
}

What the code does

Functional Options For Client Config is built around the functions WithTimeout, WithRetries, NewClient and String.

The one repetition in this snippet is the loop for _, opt := range opts.

Applying it

Entry signature: func WithTimeout(d time.Duration) Option

Running the file prints labeled results such as default:, custom: — each operation’s effect is visible in the output.

Treat main as the orchestrator calling NewClient, WithTimeout and WithRetries in a fixed order.

Statements that decide the outcome

return fmt.Sprintf("%s timeout=%s retries=%d", c.baseURL, c.timeout, c.retries)
func NewClient(baseURL string, opts ...Option) *Client {
c := &Client{baseURL: baseURL, timeout: 5 * time.Second, retries: 1}
for _, opt := range opts {
opt(c)
}
return c
}
func WithTimeout(d time.Duration) Option {
return func(c *Client) { c.timeout = d }
}

Interactive Tools for This Topic

FAQ

What does Functional Options For Client Config print when run?
Run it as a complete program — the output lines carry labels such as `default:`, `custom:`.