-
Notifications
You must be signed in to change notification settings - Fork 6
/
web_api.go
284 lines (239 loc) · 8.31 KB
/
web_api.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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
package internal
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"time"
"github.com/google/go-querystring/query"
"github.com/livechat/lc-sdk-go/v3/authorization"
api_errors "github.com/livechat/lc-sdk-go/v3/errors"
"github.com/livechat/lc-sdk-go/v3/metrics"
)
const apiVersion = "3.3"
// RetryStrategyFunc is called by each API method if set to retry when handling an error.
// If not set, there will be no retry at all.
//
// It accepts two arguments: attempts - number of sent requests (starting from 0)
// and err - error as ErrAPI struct (with StatusCode and Details)
// It returns info whether to retry the request.
type RetryStrategyFunc func(attempts uint, err error) bool
// StatsSinkFunc is called after each API method with statistics of that method execution.
type StatsSinkFunc func(callStats metrics.APICallStats)
type api struct {
httpClient *http.Client
clientID string
tokenGetter authorization.TokenGetter
httpEndpointGenerator HTTPEndpointGenerator
host string
customHeaders http.Header
retryStrategy RetryStrategyFunc
statsSink StatsSinkFunc
}
// HTTPRequestGenerator is called by each API method to generate api http url.
type HTTPEndpointGenerator func(*authorization.Token, string, string) string
type CallOptions struct {
Method string
}
// NewAPI returns ready to use raw API client. This is a base that is used internally
// by specialized clients for each API, you should use those instead
//
// If provided client is nil, then default http client with 20s timeout is used.
func NewAPI(t authorization.TokenGetter, client *http.Client, clientID string, r HTTPEndpointGenerator) (*api, error) {
if t == nil {
return nil, errors.New("cannot initialize api without TokenGetter")
}
if client == nil {
client = &http.Client{
Timeout: 20 * time.Second,
}
}
return &api{
tokenGetter: t,
clientID: clientID,
httpClient: client,
host: "https://api.livechatinc.com",
httpEndpointGenerator: r,
customHeaders: make(http.Header),
statsSink: func(metrics.APICallStats) {},
}, nil
}
// Call sends request to API with given action
func (a *api) Call(action string, reqPayload interface{}, respPayload interface{}, opts ...*CallOptions) error {
token, err := a.getToken()
if err != nil {
return err
}
start := time.Now()
endpoint := a.httpEndpointGenerator(token, a.host, action)
req, err := http.NewRequest(http.MethodPost, endpoint, nil)
if err != nil {
return fmt.Errorf("couldn't create new http request: %v", err)
}
if len(opts) > 0 && opts[0].Method == http.MethodGet {
req.Method = opts[0].Method
qs, err := query.Values(reqPayload)
if err != nil {
return err
}
encodedQuery := qs.Encode()
if req.URL.RawQuery != "" && encodedQuery != "" {
encodedQuery = "&" + encodedQuery
}
req.URL.RawQuery = req.URL.RawQuery + encodedQuery
} else {
rawBody, err := json.Marshal(reqPayload)
if err != nil {
return err
}
req.GetBody = func() (io.ReadCloser, error) {
return ioutil.NopCloser(bytes.NewReader(rawBody)), nil
}
req.Body, _ = req.GetBody()
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("%s %s", token.Type, token.AccessToken))
req.Header.Set("User-agent", fmt.Sprintf("GO SDK Application %s", a.clientID))
req.Header.Set("X-Region", token.Region)
for key, val := range a.customHeaders {
if len(val) == 0 {
continue
}
req.Header.Set(key, val[0])
}
err = a.send(req, respPayload)
executionTime := time.Now().Sub(start)
a.statsSink(metrics.APICallStats{action, executionTime, err == nil})
return err
}
// SetCustomHeader allows to set a custom header (e.g. X-Debug-Id or X-Author-Id) that will be sent in every request
func (a *api) SetCustomHeader(key, val string) {
a.customHeaders.Set(key, val)
}
// SetRetryStrategy allows to set a retry strategy that will be performed in every failed request
func (a *api) SetRetryStrategy(f RetryStrategyFunc) {
a.retryStrategy = f
}
// SetStatsSink allows to set a statistics sink that will send API calls metrics data to SDK consumers
func (a *api) SetStatsSink(f StatsSinkFunc) {
a.statsSink = f
}
type fileUploadAPI struct{ *api }
// NewAPIWithFileUpload returns ready to use raw API client with file upload functionality.
func NewAPIWithFileUpload(t authorization.TokenGetter, client *http.Client, clientID string, r HTTPEndpointGenerator) (*fileUploadAPI, error) {
api, err := NewAPI(t, client, clientID, r)
if err != nil {
return nil, err
}
return &fileUploadAPI{api}, nil
}
// UploadFile uploads a file to LiveChat CDN.
// Returned URL shall be used in call to SendFile or SendEvent or it'll become invalid
// in about 24 hours.
func (a *fileUploadAPI) UploadFile(filename string, file []byte) (string, error) {
token := a.tokenGetter()
if token == nil {
return "", fmt.Errorf("couldn't get token")
}
start := time.Now()
endpoint := a.httpEndpointGenerator(token, a.host, "upload_file")
req, err := http.NewRequest(http.MethodPost, endpoint, nil)
if err != nil {
return "", fmt.Errorf("couldn't create new http request: %v", err)
}
req.Method = "POST"
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
w, err := writer.CreateFormFile("file", filename)
if err != nil {
return "", fmt.Errorf("couldn't create form file: %v", err)
}
if _, err := w.Write(file); err != nil {
return "", fmt.Errorf("couldn't write file to multipart writer: %v", err)
}
if err := writer.Close(); err != nil {
return "", fmt.Errorf("couldn't close multipart writer: %v", err)
}
req.GetBody = func() (io.ReadCloser, error) {
return ioutil.NopCloser(bytes.NewReader(body.Bytes())), nil
}
req.Body, _ = req.GetBody()
req.Header.Set("Content-Type", writer.FormDataContentType())
req.Header.Set("Authorization", fmt.Sprintf("%s %s", token.Type, token.AccessToken))
req.Header.Set("User-agent", fmt.Sprintf("GO SDK Application %s", a.clientID))
req.Header.Set("X-Region", token.Region)
var resp struct {
URL string `json:"url"`
}
err = a.send(req, &resp)
executionTime := time.Now().Sub(start)
a.statsSink(metrics.APICallStats{"upload_file", executionTime, err == nil})
return resp.URL, err
}
func (a *api) send(req *http.Request, respPayload interface{}) error {
var attempts uint
var do func() error
do = func() error {
resp, err := a.httpClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
bodyBytes, err := ioutil.ReadAll(resp.Body)
if resp.StatusCode != http.StatusOK {
apiErr := &api_errors.ErrAPI{}
if err := json.Unmarshal(bodyBytes, apiErr); err != nil {
return fmt.Errorf("couldn't unmarshal error response: %s (code: %d, raw body: %s)", err.Error(), resp.StatusCode, string(bodyBytes))
}
if apiErr.Error() == "" {
return fmt.Errorf("couldn't unmarshal error response (code: %d, raw body: %s)", resp.StatusCode, string(bodyBytes))
}
if a.retryStrategy == nil || !a.retryStrategy(attempts, apiErr) {
return apiErr
}
token, err := a.getToken()
if err != nil {
return err
}
req.Header.Set("Authorization", fmt.Sprintf("%s %s", token.Type, token.AccessToken))
if req.Body != nil {
reqBody, err := req.GetBody()
if err != nil {
return fmt.Errorf("couldn't get request body: %v", err)
}
req.Body = reqBody
}
attempts++
return do()
}
if err != nil {
return err
}
return json.Unmarshal(bodyBytes, respPayload)
}
return do()
}
func (a *api) getToken() (*authorization.Token, error) {
token := a.tokenGetter()
if token == nil {
return nil, fmt.Errorf("couldn't get token")
}
if token.Type != authorization.BearerToken && token.Type != authorization.BasicToken {
return nil, fmt.Errorf("unsupported token type")
}
return token, nil
}
// SetCustomHost allows to change API host address. This method is mostly for LiveChat internal testing and should not be used in production environments.
func (a *api) SetCustomHost(host string) {
a.host = host
}
// DefaultHTTPRequestGenerator generates API request for given service in stable version.
func DefaultHTTPRequestGenerator(name string) HTTPEndpointGenerator {
return func(token *authorization.Token, host, action string) string {
return fmt.Sprintf("%s/v%s/%s/action/%s", host, apiVersion, name, action)
}
}