-
-
Save davidbacisin/fccaa6c7198b3b024c07beca532e2f7a to your computer and use it in GitHub Desktop.
Functional options pattern in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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