forked from andrew-waters/gomo
-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
81 lines (70 loc) · 1.7 KB
/
client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package gomo
import (
"log"
"net/http"
"os"
)
const (
defaultAPIVersion = "v2"
defaultEndpoint = "https://api.moltin.com"
defaultUserAgent = "gomo"
)
var defaultLogger = func(c *Client, msg interface{}) {
if c.Debug {
log.Println(msg)
}
}
// Client is the main client struct
type Client struct {
credentials credentials
APIVersion string
Endpoint string
AccessToken string
Debug bool
Logs []interface{}
httpClient *http.Client
Logger func(*Client, interface{})
}
// ClientOption are functions that configure a Client
type ClientOption func(*Client)
// NewClient creates a new client for you to make requests with. It is
// configured by passing in list of option functions.
func NewClient(options ...ClientOption) Client {
client := Client{
credentials: defaultCredentials(),
APIVersion: defaultAPIVersion,
Endpoint: defaultEndpoint,
Debug: false,
httpClient: &http.Client{},
Logger: defaultLogger,
}
for _, option := range options {
option(&client)
}
return client
}
// GrantType returns the string value of the current crednetials grant type
func (c *Client) GrantType() string {
return c.credentials.grantType()
}
// EnableDebug logs debugging info from the API calls
func (c *Client) EnableDebug() {
c.Debug = true
}
// DisableDebug stops logs form API calls
func (c *Client) DisableDebug() {
c.Debug = false
}
// Log will dump debug info onto stdout
func (c *Client) Log(msgs ...interface{}) {
for _, msg := range msgs {
c.Logs = append(c.Logs, msg)
c.Logger(c, msg)
}
}
func defaultCredentials() credentials {
return clientCredentials{
clientID: os.Getenv("MOLTIN_CLIENT_ID"),
clientSecret: os.Getenv("MOLTIN_CLIENT_SECRET"),
}
}