-
Notifications
You must be signed in to change notification settings - Fork 3
/
client.go
213 lines (185 loc) · 4.89 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
package gosf
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"time"
)
/************************************/
/************** CONFIG **************/
/************************************/
// Config type
type Config struct {
// auth
Host string `json:"host"`
ClientID string `json:"client_id"`
ClientSecret string `json:"client_secret"`
Username string `json:"username"`
Password string `json:"password"`
ExpiresIn int `json:"expires_in"`
// api
APIVersion int `json:"api_version"`
// proxy url
ProxyURL string `json:"proxy_url"`
}
/***********************************/
/************** TOKEN **************/
/***********************************/
// Token type.
type token struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
Signature string `json:"signature"`
ExpiresAt time.Time `json:"-"`
}
// IsExpired returns true if token has expired.
func (t *token) IsExpired() bool {
return time.Now().After(t.ExpiresAt)
}
/***********************************/
/************** OAUTH **************/
/***********************************/
// OAuth type
type oAuth struct {
*Config
*token
transport http.RoundTripper
}
func newOAuth(config *Config) *oAuth {
var proxy *url.URL
if config.ProxyURL != "" {
proxy, _ = url.Parse(config.ProxyURL)
}
return &oAuth{
Config: config,
transport: &http.Transport{
Proxy: http.ProxyURL(proxy),
},
}
}
// ExchangeToken exchange token by username and password.
// If fail, salesforce will retrun
// {
// "error": "ERROR_TYPE",
// "error_description": "ERROR_DESCRIPTION"
// }
func (o *oAuth) exchangeToken() (t *token, err error) {
u := o.Host + "/services/oauth2/token"
form := url.Values{
"grant_type": {"password"},
"client_id": {o.ClientID},
"client_secret": {o.ClientSecret},
"username": {o.Username},
"password": {o.Password},
}
resp, err := http.PostForm(u, form)
if err != nil {
return
}
decoder := json.NewDecoder(resp.Body)
if resp.StatusCode != 200 {
var authErrResp struct {
Err string `json:"error"`
ErrDescription string `json:"error_description"`
}
err = decoder.Decode(&authErrResp)
if err != nil {
return
}
err = fmt.Errorf("OAuth fail(%s): %s", authErrResp.Err, authErrResp.ErrDescription)
return
}
t = &token{
ExpiresAt: time.Now().Add(time.Second * time.Duration(o.ExpiresIn)),
}
err = decoder.Decode(t)
if err != nil {
return
}
return
}
func (o *oAuth) RoundTrip(req *http.Request) (res *http.Response, err error) {
if o.token == nil || o.token.IsExpired() {
o.token, err = o.exchangeToken()
if err != nil {
return
}
}
req.Header.Add("Authorization", o.TokenType+" "+o.AccessToken)
return o.transport.RoundTrip(req)
}
/************************************/
/************** CLIENT **************/
/************************************/
// Client Type
type Client struct {
client *http.Client
requestCtx *RequestCtx
logger Logger
}
// NewClient returns a Client instance.
func NewClient(config *Config, logger Logger) *Client {
// set logger to defaultLogger if the logger argument is nil
if logger == nil {
logger = defaultLogger
logger.Print("[logger] argument 'logger' is nil, use defaultLogger instead")
} else {
defaultLogger = logger
}
// set config.ExpiresIn default value if it's invalid
if config.ExpiresIn <= 0 {
logger.Printf("[expired time] invalid token expired time received, set to 3600s instead")
config.ExpiresIn = 3600
}
logger.Printf("[expired time] token expired after %ds and auto-refresh", config.ExpiresIn)
// set requestCtx.version to maxVersion if it is out of bound
requestCtx := &RequestCtx{
host: config.Host,
version: config.APIVersion,
}
if !requestCtx.isVersionValid() {
requestCtx.version = maxAPIVersion
logger.Printf("[api version] config.APIVersion is out of bound [%d, %d], set to %d instead", minAPIVersion, maxAPIVersion, requestCtx.version)
}
return &Client{
client: &http.Client{
Transport: newOAuth(config),
},
requestCtx: requestCtx,
logger: logger,
}
}
func (c *Client) do(op Operator) (err error) {
req, err := op.Make(&RequestCtx{
host: c.requestCtx.host,
version: c.requestCtx.version,
})
if err != nil {
return
}
httpReq, err := req.makeRequest()
if err != nil {
return
}
return c.doWithHTTPRequest(httpReq, op.Handle)
}
func (c *Client) doWithHTTPRequest(httpReq *http.Request, handler func(*http.Response) error) (err error) {
httpReq.Header.Set("Content-Type", "application/json")
resp, err := c.client.Do(httpReq)
if err != nil {
return
}
defer resp.Body.Close()
if resp.StatusCode/100 == 2 {
err = handler(resp)
} else {
err = parseErrResponse(resp)
}
return
}
// Do uses op Operator to make request, send it to salesforce,
// receieve response and pass it to the Operator to handle.
func (c *Client) Do(op Operator) error {
return c.do(op)
}