-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
92 lines (78 loc) · 1.93 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
82
83
84
85
86
87
88
89
90
91
92
package wgo
import (
"net/http"
"net/url"
"github.com/aimuz/wgo/rest"
)
const defaultBaseURL = "https://api.weixin.qq.com"
// Client is a WGo client.
type Client struct {
config clientConfig
base *url.URL
}
// ClientOption is a client option for the WGo Client config.
type ClientOption func(*clientConfig)
type clientConfig struct {
appid string
secret string
hc *http.Client
}
// NewClient ...
func NewClient(appid string, opts ...ClientOption) *Client {
base, _ := url.Parse(defaultBaseURL)
c := &Client{
base: base,
config: clientConfig{
hc: http.DefaultClient,
},
}
for _, opt := range opts {
opt(&c.config)
}
return c
}
// NewClientWithSecret ...
func NewClientWithSecret(appid string, secret string, opts ...ClientOption) *Client {
return NewClient(appid, append(opts, WithSecret(secret))...)
}
func WithSecret(secret string) ClientOption {
return func(c *clientConfig) {
c.secret = secret
}
}
// WithToken sets the token for the WGo client
func WithToken(token string) ClientOption {
return func(c *clientConfig) {
transport := c.hc.Transport
if transport == nil {
transport = http.DefaultTransport
}
c.hc.Transport = &RoundTripper{
next: transport,
TokenSource: tokenSourceFunc(func() (*Token, error) {
return &Token{AccessToken: token}, nil
}),
}
}
}
// WithHTTPClient sets the http client for the WGo client
func WithHTTPClient(client *http.Client) ClientOption {
return func(c *clientConfig) {
c.hc = client
}
}
// WithTokenSource sets the token source for the WGo client
func WithTokenSource(tokenSource TokenSource) ClientOption {
return func(c *clientConfig) {
transport := c.hc.Transport
if transport == nil {
transport = http.DefaultTransport
}
c.hc.Transport = &RoundTripper{
next: transport,
TokenSource: tokenSource,
}
}
}
// NewRequest creates a new request
func (c *Client) NewRequest() *rest.Request { return rest.NewRequest(c.base, c.config.hc) }