Skip to content

Instantly share code, notes, and snippets.

@davidbacisin
Created January 13, 2023 03:20
Show Gist options
  • Save davidbacisin/fccaa6c7198b3b024c07beca532e2f7a to your computer and use it in GitHub Desktop.
Save davidbacisin/fccaa6c7198b3b024c07beca532e2f7a to your computer and use it in GitHub Desktop.
Functional options pattern in Go
// Read about this code pattern at https://davidbacisin.com/writing/golang-options-pattern
package app
type Client struct {
baseUrl string
baseClient *http.Client
disableRedirects bool
}
type Option func(*Client)
func New(opt ...Option) *Client {
c := new(Client)
for _, o := range opt {
o(c)
}
// Set a default client if one was not provided
if c.baseClient == nil {
c.baseClient = http.DefaultClient
}
return c
}
func WithBaseUrl(url string) Option {
return func(c *Client) {
c.baseUrl = url
}
}
func WithBaseClient(base *http.Client) Option {
return func(c *Client) {
c.baseClient = base
}
}
func WithoutRedirects() Option {
return func(c *Client) {
c.disableRedirects = true
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment