Functional Options em Go


Quando você precisa construir structs com várias opções (timeouts, credenciais, flags, etc.), usar muitos parâmetros em um construtor pode deixar o código confuso. O padrão Functional Options resolve isso com funções opcionais que configuram o objeto final de forma clara, extensível e idiomática.
Option como função que recebe um ponteiro para o objeto a ser configurado.WithX(...) Option para cada configuração opcional.New...), aplique as opções antes de retornar o objeto.Isso evita construtores gigantes, facilita leitura e torna novas opções triviais de adicionar.
Vamos criar um APIClient com opções de timeout, header extra e uso de HTTPS. Cada opção é aplicada por quem constrói o cliente.
package main import ( "fmt" "net/http" "time" ) type APIClient struct { baseURL string client *http.Client headers http.Header secure bool } // Option aplica customizações ao cliente. type Option func(*APIClient) // WithTimeout altera o timeout do http.Client. func WithTimeout(d time.Duration) Option { return func(c *APIClient) { c.client.Timeout = d } } // WithHeader adiciona um header padrão. func WithHeader(key, value string) Option { return func(c *APIClient) { c.headers.Add(key, value) } } // WithSecure força HTTPS. func WithSecure() Option { return func(c *APIClient) { c.secure = true } } // NewAPIClient cria um cliente com opções. func NewAPIClient(baseURL string, opts ...Option) *APIClient { c := &APIClient{ baseURL: baseURL, client: &http.Client{Timeout: 5 * time.Second}, headers: make(http.Header), secure: false, } for _, opt := range opts { opt(c) } return c } func (c *APIClient) Endpoint(path string) string { scheme := "http" if c.secure { scheme = "https" } return fmt.Sprintf("%s://%s/%s", scheme, c.baseURL, path) } func main() { client := NewAPIClient( "api.exemplo.com", WithTimeout(10*time.Second), WithHeader("X-Client", "IPDev"), WithSecure(), ) fmt.Println("Endpoint:", client.Endpoint("users")) fmt.Println("Timeout:", client.client.Timeout) fmt.Println("Headers:", client.headers) }
NewAPIClient(..., WithTimeout(...), WithSecure()) descreve intenções.WithRetry, WithLogger, etc. sem quebrar chamadas existentes.grpc, http, sql adapters).Functional Options em Go trazem flexibilidade sem sacrificar simplicidade. Ao invés de múltiplos construtores ou structs gigantes, você compõe o objeto passo a passo, com opções nomeadas que deixam o código expressivo e fácil de manter.
When you need to construct structs with lots of optional settings (timeouts, credentials, feature flags, etc.), passing everything into a constructor quickly becomes messy. The Functional Options pattern solves this by configuring objects with optional functions like WithX(...). It’s clean, extensible, and idiomatic in Go.
Option type as a function that receives a pointer to the object being configured.WithTimeout, WithHeader, WithSecure, etc.New...) before returning the object.This avoids bloated constructors, makes calls self-documenting, and keeps adding new options painless.
Let’s build an APIClient where we can set a custom timeout, add default headers, and force HTTPS—all using functional options.
package main import ( "fmt" "net/http" "time" ) type APIClient struct { baseURL string client *http.Client headers http.Header secure bool } // Option configures the API client. type Option func(*APIClient) // WithTimeout customizes the HTTP client timeout. func WithTimeout(d time.Duration) Option { return func(c *APIClient) { c.client.Timeout = d } } // WithHeader adds a default header. func WithHeader(key, value string) Option { return func(c *APIClient) { c.headers.Add(key, value) } } // WithSecure enforces HTTPS. func WithSecure() Option { return func(c *APIClient) { c.secure = true } } // NewAPIClient constructs the client and applies options. func NewAPIClient(baseURL string, opts ...Option) *APIClient { c := &APIClient{ baseURL: baseURL, client: &http.Client{Timeout: 5 * time.Second}, headers: make(http.Header), secure: false, } for _, opt := range opts { opt(c) } return c } func (c *APIClient) Endpoint(path string) string { scheme := "http" if c.secure { scheme = "https" } return fmt.Sprintf("%s://%s/%s", scheme, c.baseURL, path) } func main() { client := NewAPIClient( "api.example.com", WithTimeout(10*time.Second), WithHeader("X-Client", "IPDev"), WithSecure(), ) fmt.Println("Endpoint:", client.Endpoint("users")) fmt.Println("Timeout:", client.client.Timeout) fmt.Println("Headers:", client.headers) }
NewAPIClient(..., WithTimeout(...), WithSecure()) tells the story.WithRetry, WithLogger, etc. with zero breaking changes.grpc, sql, http, etc.).Functional Options bring flexibility without complexity. Instead of juggling multiple constructors or huge config structs, you compose the object step by step using named options, keeping the code expressive and maintainable.