-
Notifications
You must be signed in to change notification settings - Fork 13
/
apiclient.go
255 lines (221 loc) · 6.61 KB
/
apiclient.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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
package platformclientv2
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"reflect"
"strings"
"sync/atomic"
"time"
"github.com/hashicorp/go-retryablehttp"
)
// APIClient provides functions for making API requests
type APIClient struct {
client retryablehttp.Client
configuration *Configuration
}
// NewAPIClient creates a new API client
func NewAPIClient(c *Configuration) APIClient {
timeout, err := time.ParseDuration("16s")
if err != nil {
panic(err)
}
client := retryablehttp.NewClient()
client.Logger = nil
client.HTTPClient.Timeout = timeout
return APIClient{
client: *client,
configuration: c,
}
}
// SelectHeaderContentType selects the header content type
func (c *APIClient) SelectHeaderContentType(contentTypes []string) string {
if len(contentTypes) == 0 {
return ""
}
if contains(contentTypes, "application/json") {
return "application/json"
}
return contentTypes[0] // use the first content type specified in 'consumes'
}
// SelectHeaderAccept selects the header accept
func (c *APIClient) SelectHeaderAccept(accepts []string) string {
if len(accepts) == 0 {
return ""
}
if contains(accepts, "application/json") {
return "application/json"
}
return strings.Join(accepts, ",")
}
func contains(source []string, containvalue string) bool {
for _, a := range source {
if strings.ToLower(a) == strings.ToLower(containvalue) {
return true
}
}
return false
}
// CallAPI invokes an API endpoint
func (c *APIClient) CallAPI(path string, method string,
postBody interface{},
headerParams map[string]string,
queryParams map[string]string,
formParams url.Values,
fileName string,
fileBytes []byte) (*APIResponse, error) {
// Build request URL w/query params
urlString := path + "?"
if queryParams != nil {
for k, v := range queryParams {
if v != "" {
urlString += fmt.Sprintf("%v=%v&", url.QueryEscape(strings.TrimSpace(k)), url.QueryEscape(strings.TrimSpace(v)))
}
}
}
urlString = urlString[:len(urlString)-1]
u, err := url.Parse(urlString)
if err != nil {
return nil, err
}
request := retryablehttp.Request{
Request: &http.Request{
URL: u,
Close: true,
Method: strings.ToUpper(method),
Header: make(map[string][]string),
},
}
// Set default headers
if c.configuration.DefaultHeader != nil {
for k, v := range c.configuration.DefaultHeader {
request.Header.Set(k, v)
}
}
// Set form data
if formParams != nil {
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
request.SetBody(ioutil.NopCloser(strings.NewReader(formParams.Encode())))
}
// Set post body
if postBody != nil {
request.Header.Set("Content-Type", "application/json")
j, _ := json.Marshal(postBody)
request.SetBody(ioutil.NopCloser(bytes.NewReader(j)))
}
// Set provided headers
if headerParams != nil {
for k, v := range headerParams {
request.Header.Set(k, v)
}
}
if c.configuration.RetryConfiguration == nil {
c.client.RetryMax = 0
c.client.RetryWaitMax = 0
} else {
c.client.RetryWaitMax = c.configuration.RetryConfiguration.RetryWaitMax
c.client.RetryWaitMin = c.configuration.RetryConfiguration.RetryWaitMin
c.client.RetryMax = c.configuration.RetryConfiguration.RetryMax
if c.configuration.RetryConfiguration.RequestLogHook != nil {
c.client.RequestLogHook = func(_ retryablehttp.Logger, req *http.Request, retryNumber int) {
c.configuration.RetryConfiguration.RequestLogHook(req, retryNumber)
}
}
}
requestBody, _ := request.BodyBytes()
// Execute request
res, err := c.client.Do(&request)
if err != nil {
return nil, err
}
// Read body
body, _ := ioutil.ReadAll(res.Body)
c.configuration.LoggingConfiguration.trace(method, urlString, requestBody, res.StatusCode, request.Header, res.Header)
c.configuration.LoggingConfiguration.debug(method, urlString, requestBody, res.StatusCode, request.Header)
if res.StatusCode == http.StatusUnauthorized && c.configuration.ShouldRefreshAccessToken && c.configuration.RefreshToken != "" {
err := c.handleExpiredAccessToken()
if err != nil {
return nil, err
}
if headerParams != nil {
headerParams["Authorization"] = "Bearer " + c.configuration.AccessToken
}
return c.CallAPI(path, method, postBody, headerParams, queryParams, formParams, fileName, fileBytes)
}
if res.StatusCode < http.StatusOK || res.StatusCode >= http.StatusMultipleChoices {
c.configuration.LoggingConfiguration.error(method, urlString, requestBody, body, res.StatusCode, request.Header, res.Header)
}
return NewAPIResponse(res, body)
}
func buildURL(basePath string, path string, queryParams map[string]string) (*url.URL, error) {
urlString := basePath + path
if len(queryParams) > 0 {
urlString += "?"
for k, v := range queryParams {
urlString += fmt.Sprintf("%v=%v&", strings.TrimSpace(k), strings.TrimSpace(v))
}
urlString = urlString[:len(urlString)-1]
}
u, err := url.Parse(urlString)
if err != nil {
return nil, err
}
return u, nil
}
// ParameterToString joins a parameter in the desired format
func (c *APIClient) ParameterToString(obj interface{}, collectionFormat string) string {
sep := ","
switch collectionFormat {
case "pipes":
sep = "|"
case "ssv":
sep = " "
case "tsv":
sep = "\t"
}
switch t := reflect.TypeOf(obj).String(); t {
case "[]string":
return strings.Join(obj.([]string), sep)
default:
return fmt.Sprintf("%v", obj)
}
}
func (c *APIClient) handleExpiredAccessToken() error {
if atomic.CompareAndSwapInt64(&c.configuration.RefreshInProgress, 0, 1) {
defer atomic.StoreInt64(&c.configuration.RefreshInProgress, 0)
_, err := c.configuration.RefreshAuthorizationCodeGrant(c.configuration.ClientID, c.configuration.ClientSecret, c.configuration.RefreshToken)
return err
} else {
// Wait maximum of RefreshTokenWaitTime seconds for other thread to complete refresh
startTime := time.Now().Unix()
sleepDuration := time.Millisecond * 200
// Check if we've gone over the wait threshold
for time.Now().Unix() - startTime < int64(c.configuration.RefreshTokenWaitTime) {
time.Sleep(sleepDuration) // Sleep for 200ms on every iteration
if atomic.LoadInt64(&c.configuration.RefreshInProgress) == 0 {
return nil
}
}
return fmt.Errorf("token refresh took longer than %d seconds", c.configuration.RefreshTokenWaitTime)
}
}
// Int32 is an easy way to get a pointer
func Int32(v int) *int32 {
p := int32(v)
return &p
}
// String is an easy way to get a pointer
func String(v string) *string {
return &v
}
// Bool is an easy way to get a pointer
func Bool(v bool) *bool {
return &v
}
func copy(data []byte, v interface{}) {
dataS := string(data)
reflect.ValueOf(v).Elem().Set(reflect.ValueOf(&dataS))
}