/
api_client.go
459 lines (379 loc) · 12.6 KB
/
api_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
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
/*
* --------------------------------------------------------------------------------
* <copyright company="Aspose" file="api_client.go">
* Copyright (c) 2021 Aspose.Words for Cloud
* </copyright>
* <summary>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* </summary>
* --------------------------------------------------------------------------------
*/
package api
import (
"bytes"
"context"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"mime/multipart"
"net/http"
"net/http/httputil"
"net/url"
"os"
"path/filepath"
"reflect"
"regexp"
"strconv"
"strings"
"time"
"unicode/utf8"
"golang.org/x/oauth2"
"github.com/aspose-words-cloud/aspose-words-cloud-go/v2103/api/models"
)
var (
jsonCheck = regexp.MustCompile("(?i:[application|text]/json)")
xmlCheck = regexp.MustCompile("(?i:[application|text]/xml)")
)
// APIClient manages communication with the Aspose.Words for Cloud API Reference API v21.3
// In most cases there should be only one, shared, APIClient.
type APIClient struct {
cfg *models.Configuration
common service // Reuse a single struct instead of allocating one for each service on the heap.
// API Services
WordsApi *WordsApiService
}
type service struct {
client *APIClient
}
// NewAPIClient creates a new API client. Requires a userAgent string describing your application.
// optionally a custom http.Client to allow for advanced features such as caching.
func NewAPIClient(cfg *models.Configuration) (client *APIClient, err error) {
if cfg.HttpClient == nil {
cfg.HttpClient = http.DefaultClient
}
if cfg.ClientId == "" {
return nil, errors.New("ClientId must be non-empty string")
}
if cfg.ClientSecret == "" {
return nil, errors.New("ClientSecret must be non-empty string")
}
_, urlErr := url.ParseRequestURI(cfg.BaseUrl)
if urlErr != nil {
return nil, errors.New("BaseUrl must be valid URL")
}
c := &APIClient{}
c.cfg = cfg
c.common.client = c
// API Services
c.WordsApi = (*WordsApiService)(&c.common)
return c, nil
}
func atoi(in string) (int, error) {
return strconv.Atoi(in)
}
// callAPI do the request.
func (c *APIClient) callAPI(request *http.Request) (resp *http.Response, err error) {
// log request
if c.cfg.DebugMode {
dumpRequest, err := httputil.DumpRequest(request, true)
if err != nil {
return nil, err
}
log.Print(string(dumpRequest))
}
response, err := c.cfg.HttpClient.Do(request)
if err != nil {
return response, err
}
if c.cfg.DebugMode {
dumpResponse, err := httputil.DumpResponse(response, true)
if err != nil {
return nil, err
}
log.Print(string(dumpResponse))
}
return response, err
}
// Change base path to allow switching to mocks
func (c *APIClient) ChangeBasePath(path string) {
c.cfg.BaseUrl = path
}
// create context with token
func (c *APIClient) NewContextWithToken(ctx context.Context) (ctxWithToken context.Context, err error) {
type authResponse struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
}
if ctx == nil {
ctx = context.Background()
}
tokenUrl, _ := url.Parse(c.cfg.BaseUrl)
tokenUrl.Path = "/connect/token"
response, err := http.PostForm(tokenUrl.String(), url.Values{
"grant_type": {"client_credentials"},
"client_id": {c.cfg.ClientId},
"client_secret": {c.cfg.ClientSecret},
})
// http error
if err != nil {
return nil, err
}
if response.StatusCode != 200 {
return nil, errors.New(fmt.Sprintf("Get a token request failed: %s returned %d status", tokenUrl.String(), response.StatusCode))
}
defer response.Body.Close()
jsonData, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, err
}
var result authResponse
parseErr := json.Unmarshal(jsonData, &result)
if parseErr != nil {
return nil, err
}
return context.WithValue(ctx, models.ContextAccessToken, result.AccessToken), nil
}
// prepareRequest build the request
func (c *APIClient) prepareRequest (
ctx context.Context,
data models.RequestData) (request *http.Request, err error) {
var body *bytes.Buffer
// Detect postBody type and post.
if data.PostBody != nil {
contentType := data.HeaderParams["Content-Type"]
if contentType == "" {
contentType = detectContentType(data.PostBody)
data.HeaderParams["Content-Type"] = contentType
}
body, err = setBody(data.PostBody, contentType)
if err != nil {
return nil, err
}
}
// add form parameters and file if available.
if len(data.FormParams) > 0 {
if body != nil {
return nil, errors.New("Cannot specify postBody and multipart form at the same time.")
}
body = &bytes.Buffer{}
w := multipart.NewWriter(body)
data.HeaderParams["Content-Type"] = w.FormDataContentType()
for _, fp := range data.FormParams {
if fp.IsFile {
if len(fp.File) > 0 && fp.Name != "" {
w.Boundary()
part, err := w.CreateFormFile(fp.Name, filepath.Base(fp.Name))
if err != nil {
return nil, err
}
_, err = part.Write(fp.File)
if err != nil {
return nil, err
}
}
} else {
w.WriteField(fp.Name, fp.Text)
}
}
// Set Content-Length
data.HeaderParams["Content-Length"] = fmt.Sprintf("%d", body.Len())
w.Close()
}
// Setup path and query parameters
url, err := url.Parse(data.Path)
if err != nil {
return nil, err
}
// Adding Query Param
query := url.Query()
for k, v := range data.QueryParams {
for _, iv := range v {
query.Add(k, iv)
}
}
// Encode the parameters.
url.RawQuery = query.Encode()
// Generate a new request
if body != nil {
request, err = http.NewRequest(data.Method, url.String(), body)
} else {
request, err = http.NewRequest(data.Method, url.String(), nil)
}
if err != nil {
return nil, err
}
// add header parameters, if any
if len(data.HeaderParams) > 0 {
headers := http.Header{}
for h, v := range data.HeaderParams {
headers.Set(h, v)
}
request.Header = headers
}
if ctx != nil {
// add context to the request
request = request.WithContext(ctx)
// Walk through any authentication.
// OAuth2 authentication
if tok, ok := ctx.Value(models.ContextOAuth2).(oauth2.TokenSource); ok {
// We were able to grab an oauth2 token from the context
var latestToken *oauth2.Token
if latestToken, err = tok.Token(); err != nil {
return nil, err
}
latestToken.SetAuthHeader(request)
}
// Basic HTTP Authentication
if auth, ok := ctx.Value(models.ContextBasicAuth).(models.BasicAuth); ok {
request.SetBasicAuth(auth.UserName, auth.Password)
}
// AccessToken Authentication
if auth, ok := ctx.Value(models.ContextAccessToken).(string); ok {
request.Header.Add("Authorization", "Bearer " + auth)
}
}
for header, value := range c.cfg.DefaultHeader {
request.Header.Add(header, value)
}
return request, nil
}
// Add a file to the multipart request
func addFile(w *multipart.Writer, fieldName, path string) error {
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()
part, err := w.CreateFormFile(fieldName, filepath.Base(path))
if err != nil {
return err
}
_, err = io.Copy(part, file)
return err
}
// Prevent trying to import "fmt"
func reportError(format string, a ...interface{}) (error) {
return fmt.Errorf(format, a...)
}
// Set request body from an interface{}
func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err error) {
if bodyBuf == nil {
bodyBuf = &bytes.Buffer{}
}
if reader, ok := body.(io.Reader); ok {
_, err = bodyBuf.ReadFrom(reader)
} else if b, ok := body.([]byte); ok {
_, err = bodyBuf.Write(b)
} else if s, ok := body.(string); ok {
_, err = bodyBuf.WriteString(s)
} else if jsonCheck.MatchString(contentType) {
err = json.NewEncoder(bodyBuf).Encode(body)
} else if xmlCheck.MatchString(contentType) {
xml.NewEncoder(bodyBuf).Encode(body)
}
if err != nil {
return nil, err
}
if bodyBuf.Len() == 0 {
err = fmt.Errorf("Invalid body type %s\n", contentType)
return nil, err
}
return bodyBuf, nil
}
// detectContentType method is used to figure out `Request.Body` content type for request header
func detectContentType(body interface{}) string {
contentType := "text/plain; charset=utf-8"
kind := reflect.TypeOf(body).Kind()
switch kind {
case reflect.Struct, reflect.Map, reflect.Ptr:
contentType = "application/json; charset=utf-8"
case reflect.String:
contentType = "text/plain; charset=utf-8"
default:
if b, ok := body.([]byte); ok {
contentType = http.DetectContentType(b)
} else if kind == reflect.Slice {
contentType = "application/json; charset=utf-8"
}
}
return contentType
}
// Ripped from https://github.com/gregjones/httpcache/blob/master/httpcache.go
type cacheControl map[string]string
func parseCacheControl(headers http.Header) cacheControl {
cc := cacheControl{}
ccHeader := headers.Get("Cache-Control")
for _, part := range strings.Split(ccHeader, ",") {
part = strings.Trim(part, " ")
if part == "" {
continue
}
if strings.ContainsRune(part, '=') {
keyval := strings.Split(part, "=")
cc[strings.Trim(keyval[0], " ")] = strings.Trim(keyval[1], ",")
} else {
cc[part] = ""
}
}
return cc
}
// CacheExpires helper function to determine remaining time before repeating a request.
func CacheExpires(r *http.Response) (time.Time) {
// Figure out when the cache expires.
var expires time.Time
now, err := time.Parse(time.RFC1123, r.Header.Get("date"))
if err != nil {
return time.Now()
}
respCacheControl := parseCacheControl(r.Header)
if maxAge, ok := respCacheControl["max-age"]; ok {
lifetime, err := time.ParseDuration(maxAge + "s")
if err != nil {
expires = now
}
expires = now.Add(lifetime)
} else {
expiresHeader := r.Header.Get("Expires")
if expiresHeader != "" {
expires, err = time.Parse(time.RFC1123, expiresHeader)
if err != nil {
expires = now
}
}
}
return expires
}
func strlen(s string) (int) {
return utf8.RuneCountInString(s)
}
func CreateWordsApi(config *models.Configuration) (wordsApi *WordsApiService, ctxWithToken context.Context, err error) {
client, err := NewAPIClient(config)
if err != nil {
return nil, nil, err
}
ctx, err := client.NewContextWithToken(nil)
if err != nil {
return nil, nil, err
}
return client.WordsApi, ctx, err
}