Use functional options pattern
This commit is contained in:
parent
6debdd8ba6
commit
2a663690a8
40
client.go
40
client.go
@ -9,29 +9,39 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
)
|
)
|
||||||
|
|
||||||
type ClientOptions struct {
|
|
||||||
BaseUrl string
|
|
||||||
ApiKey string
|
|
||||||
}
|
|
||||||
|
|
||||||
type Client struct {
|
type Client struct {
|
||||||
BaseUrl string
|
BaseUrl string
|
||||||
ApiUrl string
|
ApiUrl string
|
||||||
ApiKey string
|
ApiKey string
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewClient(options *ClientOptions) *Client {
|
func NewClient(options ...func(*Client)) *Client {
|
||||||
if options.BaseUrl == "" {
|
c := &Client{}
|
||||||
options.BaseUrl = "https://stacker.news"
|
for _, o := range options {
|
||||||
}
|
o(c)
|
||||||
if options.ApiKey == "" {
|
|
||||||
options.ApiKey = os.Getenv("SN_API_KEY")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return &Client{
|
// set defaults
|
||||||
BaseUrl: options.BaseUrl,
|
if c.BaseUrl == "" {
|
||||||
ApiUrl: fmt.Sprintf("%s/api/graphql", options.BaseUrl),
|
c.BaseUrl = "https://stacker.news"
|
||||||
ApiKey: options.ApiKey,
|
}
|
||||||
|
if c.ApiKey == "" {
|
||||||
|
c.ApiKey = os.Getenv("SN_API_KEY")
|
||||||
|
}
|
||||||
|
c.ApiUrl = fmt.Sprintf("%s/api/graphql", c.BaseUrl)
|
||||||
|
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
|
||||||
|
func WithApiKey(apiKey string) func(*Client) {
|
||||||
|
return func(c *Client) {
|
||||||
|
c.ApiKey = apiKey
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func WithBaseUrl(baseUrl string) func(*Client) {
|
||||||
|
return func(c *Client) {
|
||||||
|
c.BaseUrl = baseUrl
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user