Functional Options For Client Config
Variadic Option closures applied over defaults make client constructors extensible: callers override only the knobs they care about.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.