mirror of
https://github.com/retailcrm/mg-bot-api-client-go.git
synced 2024-11-21 20:36:05 +03:00
Add functional options for MGClient
This commit is contained in:
parent
4058284e32
commit
9ecd6f85a1
34
v1/client.go
34
v1/client.go
@ -14,16 +14,46 @@ import (
|
||||
"github.com/google/go-querystring/query"
|
||||
)
|
||||
|
||||
type Option func(*MgClient)
|
||||
|
||||
// OptionHTTPClient set custom http.Client for MgClient
|
||||
func OptionHTTPClient(client *http.Client) func(*MgClient) {
|
||||
return func(c *MgClient) {
|
||||
c.httpClient = client
|
||||
}
|
||||
}
|
||||
|
||||
// OptionLogger sets the provided logger instance into the MgClient
|
||||
func OptionLogger(logger BasicLogger) func(*MgClient) {
|
||||
return func(c *MgClient) {
|
||||
c.logger = logger
|
||||
}
|
||||
}
|
||||
|
||||
// OptionDebug enables debug mode for MgClient
|
||||
func OptionDebug() func(*MgClient) {
|
||||
return func(c *MgClient) {
|
||||
c.Debug = true
|
||||
}
|
||||
}
|
||||
|
||||
// New initialize client
|
||||
func New(url string, token string) *MgClient {
|
||||
return &MgClient{
|
||||
func New(url string, token string, opts ...Option) *MgClient {
|
||||
c := &MgClient{
|
||||
URL: url,
|
||||
Token: token,
|
||||
httpClient: &http.Client{Timeout: time.Minute},
|
||||
}
|
||||
|
||||
for _, opt := range opts {
|
||||
opt(c)
|
||||
}
|
||||
|
||||
return c
|
||||
}
|
||||
|
||||
// WithLogger sets the provided logger instance into the Client.
|
||||
// Deprecated: Use functional option OptionLogger instead
|
||||
func (c *MgClient) WithLogger(logger BasicLogger) *MgClient {
|
||||
c.logger = logger
|
||||
return c
|
||||
|
@ -44,14 +44,12 @@ var (
|
||||
debug, _ = strconv.ParseBool(os.Getenv("DEBUG"))
|
||||
)
|
||||
|
||||
func client() *MgClient {
|
||||
c := New(mgURL, mgToken)
|
||||
|
||||
func client(opts ...Option) *MgClient {
|
||||
if debug != false {
|
||||
c.Debug = true
|
||||
opts = append(opts, OptionDebug())
|
||||
}
|
||||
|
||||
return c
|
||||
return New(mgURL, mgToken, opts...)
|
||||
}
|
||||
|
||||
func TestMgClient_Bots(t *testing.T) {
|
||||
@ -898,9 +896,7 @@ func TestMgClient_DebugWithLogger(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
logger := log.New(&buf, "Custom log prefix ", 0)
|
||||
|
||||
c := client()
|
||||
c.Debug = true
|
||||
c.WithLogger(logger)
|
||||
c := client(OptionDebug(), OptionLogger(logger))
|
||||
|
||||
c.writeLog("Test log string")
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user