-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
806 lines (675 loc) · 27.5 KB
/
client.go
File metadata and controls
806 lines (675 loc) · 27.5 KB
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
/*
OpenProject API V3 (Stable)
You're looking at the current **stable** documentation of the OpenProject APIv3. If you're interested in the current development version, please go to [github.com/opf](https://github.com/opf/openproject/tree/dev/docs/api/apiv3). ## Introduction The documentation for the APIv3 is written according to the [OpenAPI 3.0 Specification](https://swagger.io/specification/). You can either view the static version of this documentation on the [website](https://www.openproject.org/docs/api/introduction/) or the interactive version, rendered with [OpenAPI Explorer](https://github.com/Rhosys/openapi-explorer/blob/main/README.md), in your OpenProject installation under `/api/docs`. In the latter you can try out the various API endpoints directly interacting with our OpenProject data. Moreover you can access the specification source itself under `/api/v3/spec.json` and `/api/v3/spec.yml` (e.g. [here](https://community.openproject.org/api/v3/spec.yml)). The APIv3 is a hypermedia REST API, a shorthand for \"Hypermedia As The Engine Of Application State\" (HATEOAS). This means that each endpoint of this API will have links to other resources or actions defined in the resulting body. These related resources and actions for any given resource will be context sensitive. For example, only actions that the authenticated user can take are being rendered. This can be used to dynamically identify actions that the user might take for any given response. As an example, if you fetch a work package through the [Work Package endpoint](https://www.openproject.org/docs/api/endpoints/work-packages/), the `update` link will only be present when the user you authenticated has been granted a permission to update the work package in the assigned project. ## HAL+JSON HAL is a simple format that gives a consistent and easy way to hyperlink between resources in your API. Read more in the following specification: [https://tools.ietf.org/html/draft-kelly-json-hal-08](https://tools.ietf.org/html/draft-kelly-json-hal-08) **OpenProject API implementation of HAL+JSON format** enriches JSON and introduces a few meta properties: - `_type` - specifies the type of the resource (e.g.: WorkPackage, Project) - `_links` - contains all related resource and action links available for the resource - `_embedded` - contains all embedded objects HAL does not guarantee that embedded resources are embedded in their full representation, they might as well be partially represented (e.g. some properties can be left out). However in this API you have the guarantee that whenever a resource is **embedded**, it is embedded in its **full representation**. ## API response structure All API responses contain a single HAL+JSON object, even collections of objects are technically represented by a single HAL+JSON object that itself contains its members. More details on collections can be found in the [Collections Section](https://www.openproject.org/docs/api/collections/). ## Authentication The API supports the following authentication schemes: OAuth2, session based authentication, and basic auth. Depending on the settings of the OpenProject instance many resources can be accessed without being authenticated. In case the instance requires authentication on all requests the client will receive an **HTTP 401** status code in response to any request. Otherwise unauthenticated clients have all the permissions of the anonymous user. ### Session-based Authentication This means you have to login to OpenProject via the Web-Interface to be authenticated in the API. This method is well-suited for clients acting within the browser, like the Angular-Client built into OpenProject. In this case, you always need to pass the HTTP header `X-Requested-With \"XMLHttpRequest\"` for authentication. ### API Key through Basic Auth Users can authenticate towards the API v3 using basic auth with the user name `apikey` (NOT your login) and the API key as the password. Users can find their API key on their account page. Example: ```shell API_KEY=2519132cdf62dcf5a66fd96394672079f9e9cad1 curl -u apikey:$API_KEY https://community.openproject.org/api/v3/users/42 ``` ### OAuth2.0 authentication OpenProject allows authentication and authorization with OAuth2 with *Authorization code flow*, as well as *Client credentials* operation modes. To get started, you first need to register an application in the OpenProject OAuth administration section of your installation. This will save an entry for your application with a client unique identifier (`client_id`) and an accompanying secret key (`client_secret`). You can then use one the following guides to perform the supported OAuth 2.0 flows: - [Authorization code flow](https://oauth.net/2/grant-types/authorization-code) - [Authorization code flow with PKCE](https://doorkeeper.gitbook.io/guides/ruby-on-rails/pkce-flow), recommended for clients unable to keep the client_secret confidential. - [Client credentials](https://oauth.net/2/grant-types/client-credentials/) - Requires an application to be bound to an impersonating user for non-public access ### Why not username and password? The simplest way to do basic auth would be to use a user's username and password naturally. However, OpenProject already has supported API keys in the past for the API v2, though not through basic auth. Using **username and password** directly would have some advantages: * It is intuitive for the user who then just has to provide those just as they would when logging into OpenProject. * No extra logic for token management necessary. On the other hand using **API keys** has some advantages too, which is why we went for that: * If compromised while saved on an insecure client the user only has to regenerate the API key instead of changing their password, too. * They are naturally long and random which makes them invulnerable to dictionary attacks and harder to crack in general. Most importantly users may not actually have a password to begin with. Specifically when they have registered through an OpenID Connect provider. ## Cross-Origin Resource Sharing (CORS) By default, the OpenProject API is _not_ responding with any CORS headers. If you want to allow cross-domain AJAX calls against your OpenProject instance, you need to enable CORS headers being returned. Please see [our API settings documentation](https://www.openproject.org/docs/system-admin-guide/api-and-webhooks/) on how to selectively enable CORS. ## Allowed HTTP methods - `GET` - Get a single resource or collection of resources - `POST` - Create a new resource or perform - `PATCH` - Update a resource - `DELETE` - Delete a resource ## Compression Responses are compressed if requested by the client. Currently [gzip](https://www.gzip.org/) and [deflate](https://tools.ietf.org/html/rfc1951) are supported. The client signals the desired compression by setting the [`Accept-Encoding` header](https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3). If no `Accept-Encoding` header is send, `Accept-Encoding: identity` is assumed which will result in the API responding uncompressed.
API version: 3
*/
// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT.
package openproject
import (
"bytes"
"context"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io"
"log"
"mime/multipart"
"net/http"
"net/http/httputil"
"net/url"
"os"
"path/filepath"
"reflect"
"regexp"
"strconv"
"strings"
"time"
"unicode/utf8"
)
var (
JsonCheck = regexp.MustCompile(`(?i:(?:application|text)/(?:[^;]+\+)?json)`)
XmlCheck = regexp.MustCompile(`(?i:(?:application|text)/(?:[^;]+\+)?xml)`)
queryParamSplit = regexp.MustCompile(`(^|&)([^&]+)`)
queryDescape = strings.NewReplacer( "%5B", "[", "%5D", "]" )
)
// APIClient manages communication with the OpenProject API V3 (Stable) API v3
// In most cases there should be only one, shared, APIClient.
type APIClient struct {
cfg *Configuration
common service // Reuse a single struct instead of allocating one for each service on the heap.
// API Services
ActionsCapabilitiesAPI *ActionsCapabilitiesAPIService
ActivitiesAPI *ActivitiesAPIService
AttachmentsAPI *AttachmentsAPIService
BudgetsAPI *BudgetsAPIService
CategoriesAPI *CategoriesAPIService
CollectionsAPI *CollectionsAPIService
ConfigurationAPI *ConfigurationAPIService
CustomActionsAPI *CustomActionsAPIService
CustomOptionsAPI *CustomOptionsAPIService
DocumentsAPI *DocumentsAPIService
FileLinksAPI *FileLinksAPIService
FormsAPI *FormsAPIService
GridsAPI *GridsAPIService
GroupsAPI *GroupsAPIService
HelpTextsAPI *HelpTextsAPIService
MeetingsAPI *MeetingsAPIService
MembershipsAPI *MembershipsAPIService
NewsAPI *NewsAPIService
NotificationsAPI *NotificationsAPIService
OAuth2API *OAuth2APIService
PostsAPI *PostsAPIService
PreviewingAPI *PreviewingAPIService
PrincipalsAPI *PrincipalsAPIService
PrioritiesAPI *PrioritiesAPIService
ProjectsAPI *ProjectsAPIService
QueriesAPI *QueriesAPIService
QueryColumnsAPI *QueryColumnsAPIService
QueryFilterInstanceSchemaAPI *QueryFilterInstanceSchemaAPIService
QueryFiltersAPI *QueryFiltersAPIService
QueryOperatorsAPI *QueryOperatorsAPIService
QuerySortBysAPI *QuerySortBysAPIService
RelationsAPI *RelationsAPIService
RevisionsAPI *RevisionsAPIService
RolesAPI *RolesAPIService
RootAPI *RootAPIService
SchemasAPI *SchemasAPIService
StatusesAPI *StatusesAPIService
TimeEntriesAPI *TimeEntriesAPIService
TimeEntryActivitiesAPI *TimeEntryActivitiesAPIService
TypesAPI *TypesAPIService
UserPreferencesAPI *UserPreferencesAPIService
UsersAPI *UsersAPIService
ValuesPropertyAPI *ValuesPropertyAPIService
VersionsAPI *VersionsAPIService
ViewsAPI *ViewsAPIService
WikiPagesAPI *WikiPagesAPIService
WorkPackagesAPI *WorkPackagesAPIService
WorkScheduleAPI *WorkScheduleAPIService
}
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 *Configuration) *APIClient {
if cfg.HTTPClient == nil {
cfg.HTTPClient = http.DefaultClient
}
c := &APIClient{}
c.cfg = cfg
c.common.client = c
// API Services
c.ActionsCapabilitiesAPI = (*ActionsCapabilitiesAPIService)(&c.common)
c.ActivitiesAPI = (*ActivitiesAPIService)(&c.common)
c.AttachmentsAPI = (*AttachmentsAPIService)(&c.common)
c.BudgetsAPI = (*BudgetsAPIService)(&c.common)
c.CategoriesAPI = (*CategoriesAPIService)(&c.common)
c.CollectionsAPI = (*CollectionsAPIService)(&c.common)
c.ConfigurationAPI = (*ConfigurationAPIService)(&c.common)
c.CustomActionsAPI = (*CustomActionsAPIService)(&c.common)
c.CustomOptionsAPI = (*CustomOptionsAPIService)(&c.common)
c.DocumentsAPI = (*DocumentsAPIService)(&c.common)
c.FileLinksAPI = (*FileLinksAPIService)(&c.common)
c.FormsAPI = (*FormsAPIService)(&c.common)
c.GridsAPI = (*GridsAPIService)(&c.common)
c.GroupsAPI = (*GroupsAPIService)(&c.common)
c.HelpTextsAPI = (*HelpTextsAPIService)(&c.common)
c.MeetingsAPI = (*MeetingsAPIService)(&c.common)
c.MembershipsAPI = (*MembershipsAPIService)(&c.common)
c.NewsAPI = (*NewsAPIService)(&c.common)
c.NotificationsAPI = (*NotificationsAPIService)(&c.common)
c.OAuth2API = (*OAuth2APIService)(&c.common)
c.PostsAPI = (*PostsAPIService)(&c.common)
c.PreviewingAPI = (*PreviewingAPIService)(&c.common)
c.PrincipalsAPI = (*PrincipalsAPIService)(&c.common)
c.PrioritiesAPI = (*PrioritiesAPIService)(&c.common)
c.ProjectsAPI = (*ProjectsAPIService)(&c.common)
c.QueriesAPI = (*QueriesAPIService)(&c.common)
c.QueryColumnsAPI = (*QueryColumnsAPIService)(&c.common)
c.QueryFilterInstanceSchemaAPI = (*QueryFilterInstanceSchemaAPIService)(&c.common)
c.QueryFiltersAPI = (*QueryFiltersAPIService)(&c.common)
c.QueryOperatorsAPI = (*QueryOperatorsAPIService)(&c.common)
c.QuerySortBysAPI = (*QuerySortBysAPIService)(&c.common)
c.RelationsAPI = (*RelationsAPIService)(&c.common)
c.RevisionsAPI = (*RevisionsAPIService)(&c.common)
c.RolesAPI = (*RolesAPIService)(&c.common)
c.RootAPI = (*RootAPIService)(&c.common)
c.SchemasAPI = (*SchemasAPIService)(&c.common)
c.StatusesAPI = (*StatusesAPIService)(&c.common)
c.TimeEntriesAPI = (*TimeEntriesAPIService)(&c.common)
c.TimeEntryActivitiesAPI = (*TimeEntryActivitiesAPIService)(&c.common)
c.TypesAPI = (*TypesAPIService)(&c.common)
c.UserPreferencesAPI = (*UserPreferencesAPIService)(&c.common)
c.UsersAPI = (*UsersAPIService)(&c.common)
c.ValuesPropertyAPI = (*ValuesPropertyAPIService)(&c.common)
c.VersionsAPI = (*VersionsAPIService)(&c.common)
c.ViewsAPI = (*ViewsAPIService)(&c.common)
c.WikiPagesAPI = (*WikiPagesAPIService)(&c.common)
c.WorkPackagesAPI = (*WorkPackagesAPIService)(&c.common)
c.WorkScheduleAPI = (*WorkScheduleAPIService)(&c.common)
return c
}
func atoi(in string) (int, error) {
return strconv.Atoi(in)
}
// selectHeaderContentType select a content type from the available list.
func 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 join all accept types and return
func selectHeaderAccept(accepts []string) string {
if len(accepts) == 0 {
return ""
}
if contains(accepts, "application/json") {
return "application/json"
}
return strings.Join(accepts, ",")
}
// contains is a case insensitive match, finding needle in a haystack
func contains(haystack []string, needle string) bool {
for _, a := range haystack {
if strings.EqualFold(a, needle) {
return true
}
}
return false
}
// Verify optional parameters are of the correct type.
func typeCheckParameter(obj interface{}, expected string, name string) error {
// Make sure there is an object.
if obj == nil {
return nil
}
// Check the type is as expected.
if reflect.TypeOf(obj).String() != expected {
return fmt.Errorf("expected %s to be of type %s but received %s", name, expected, reflect.TypeOf(obj).String())
}
return nil
}
func parameterValueToString( obj interface{}, key string ) string {
if reflect.TypeOf(obj).Kind() != reflect.Ptr {
return fmt.Sprintf("%v", obj)
}
var param,ok = obj.(MappedNullable)
if !ok {
return ""
}
dataMap,err := param.ToMap()
if err != nil {
return ""
}
return fmt.Sprintf("%v", dataMap[key])
}
// parameterAddToHeaderOrQuery adds the provided object to the request header or url query
// supporting deep object syntax
func parameterAddToHeaderOrQuery(headerOrQueryParams interface{}, keyPrefix string, obj interface{}, collectionType string) {
var v = reflect.ValueOf(obj)
var value = ""
if v == reflect.ValueOf(nil) {
value = "null"
} else {
switch v.Kind() {
case reflect.Invalid:
value = "invalid"
case reflect.Struct:
if t,ok := obj.(MappedNullable); ok {
dataMap,err := t.ToMap()
if err != nil {
return
}
parameterAddToHeaderOrQuery(headerOrQueryParams, keyPrefix, dataMap, collectionType)
return
}
if t, ok := obj.(time.Time); ok {
parameterAddToHeaderOrQuery(headerOrQueryParams, keyPrefix, t.Format(time.RFC3339Nano), collectionType)
return
}
value = v.Type().String() + " value"
case reflect.Slice:
var indValue = reflect.ValueOf(obj)
if indValue == reflect.ValueOf(nil) {
return
}
var lenIndValue = indValue.Len()
for i:=0;i<lenIndValue;i++ {
var arrayValue = indValue.Index(i)
parameterAddToHeaderOrQuery(headerOrQueryParams, keyPrefix, arrayValue.Interface(), collectionType)
}
return
case reflect.Map:
var indValue = reflect.ValueOf(obj)
if indValue == reflect.ValueOf(nil) {
return
}
iter := indValue.MapRange()
for iter.Next() {
k,v := iter.Key(), iter.Value()
parameterAddToHeaderOrQuery(headerOrQueryParams, fmt.Sprintf("%s[%s]", keyPrefix, k.String()), v.Interface(), collectionType)
}
return
case reflect.Interface:
fallthrough
case reflect.Ptr:
parameterAddToHeaderOrQuery(headerOrQueryParams, keyPrefix, v.Elem().Interface(), collectionType)
return
case reflect.Int, reflect.Int8, reflect.Int16,
reflect.Int32, reflect.Int64:
value = strconv.FormatInt(v.Int(), 10)
case reflect.Uint, reflect.Uint8, reflect.Uint16,
reflect.Uint32, reflect.Uint64, reflect.Uintptr:
value = strconv.FormatUint(v.Uint(), 10)
case reflect.Float32, reflect.Float64:
value = strconv.FormatFloat(v.Float(), 'g', -1, 32)
case reflect.Bool:
value = strconv.FormatBool(v.Bool())
case reflect.String:
value = v.String()
default:
value = v.Type().String() + " value"
}
}
switch valuesMap := headerOrQueryParams.(type) {
case url.Values:
if collectionType == "csv" && valuesMap.Get(keyPrefix) != "" {
valuesMap.Set(keyPrefix, valuesMap.Get(keyPrefix) + "," + value)
} else {
valuesMap.Add(keyPrefix, value)
}
break
case map[string]string:
valuesMap[keyPrefix] = value
break
}
}
// helper for converting interface{} parameters to json strings
func parameterToJson(obj interface{}) (string, error) {
jsonBuf, err := json.Marshal(obj)
if err != nil {
return "", err
}
return string(jsonBuf), err
}
// callAPI do the request.
func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) {
if c.cfg.Debug {
dump, err := httputil.DumpRequestOut(request, true)
if err != nil {
return nil, err
}
log.Printf("\n%s\n", string(dump))
}
resp, err := c.cfg.HTTPClient.Do(request)
if err != nil {
return resp, err
}
if c.cfg.Debug {
dump, err := httputil.DumpResponse(resp, true)
if err != nil {
return resp, err
}
log.Printf("\n%s\n", string(dump))
}
return resp, err
}
// Allow modification of underlying config for alternate implementations and testing
// Caution: modifying the configuration while live can cause data races and potentially unwanted behavior
func (c *APIClient) GetConfig() *Configuration {
return c.cfg
}
type formFile struct {
fileBytes []byte
fileName string
formFileName string
}
// prepareRequest build the request
func (c *APIClient) prepareRequest(
ctx context.Context,
path string, method string,
postBody interface{},
headerParams map[string]string,
queryParams url.Values,
formParams url.Values,
formFiles []formFile) (localVarRequest *http.Request, err error) {
var body *bytes.Buffer
// Detect postBody type and post.
if postBody != nil {
contentType := headerParams["Content-Type"]
if contentType == "" {
contentType = detectContentType(postBody)
headerParams["Content-Type"] = contentType
}
body, err = setBody(postBody, contentType)
if err != nil {
return nil, err
}
}
// add form parameters and file if available.
if strings.HasPrefix(headerParams["Content-Type"], "multipart/form-data") && len(formParams) > 0 || (len(formFiles) > 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)
for k, v := range formParams {
for _, iv := range v {
if strings.HasPrefix(k, "@") { // file
err = addFile(w, k[1:], iv)
if err != nil {
return nil, err
}
} else { // form value
w.WriteField(k, iv)
}
}
}
for _, formFile := range formFiles {
if len(formFile.fileBytes) > 0 && formFile.fileName != "" {
w.Boundary()
part, err := w.CreateFormFile(formFile.formFileName, filepath.Base(formFile.fileName))
if err != nil {
return nil, err
}
_, err = part.Write(formFile.fileBytes)
if err != nil {
return nil, err
}
}
}
// Set the Boundary in the Content-Type
headerParams["Content-Type"] = w.FormDataContentType()
// Set Content-Length
headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len())
w.Close()
}
if strings.HasPrefix(headerParams["Content-Type"], "application/x-www-form-urlencoded") && len(formParams) > 0 {
if body != nil {
return nil, errors.New("Cannot specify postBody and x-www-form-urlencoded form at the same time.")
}
body = &bytes.Buffer{}
body.WriteString(formParams.Encode())
// Set Content-Length
headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len())
}
// Setup path and query parameters
url, err := url.Parse(path)
if err != nil {
return nil, err
}
// Override request host, if applicable
if c.cfg.Host != "" {
url.Host = c.cfg.Host
}
// Override request scheme, if applicable
if c.cfg.Scheme != "" {
url.Scheme = c.cfg.Scheme
}
// Adding Query Param
query := url.Query()
for k, v := range queryParams {
for _, iv := range v {
query.Add(k, iv)
}
}
// Encode the parameters.
url.RawQuery = queryParamSplit.ReplaceAllStringFunc(query.Encode(), func(s string) string {
pieces := strings.Split(s, "=")
pieces[0] = queryDescape.Replace(pieces[0])
return strings.Join(pieces, "=")
})
// Generate a new request
if body != nil {
localVarRequest, err = http.NewRequest(method, url.String(), body)
} else {
localVarRequest, err = http.NewRequest(method, url.String(), nil)
}
if err != nil {
return nil, err
}
// add header parameters, if any
if len(headerParams) > 0 {
headers := http.Header{}
for h, v := range headerParams {
headers[h] = []string{v}
}
localVarRequest.Header = headers
}
// Add the user agent to the request.
localVarRequest.Header.Add("User-Agent", c.cfg.UserAgent)
if ctx != nil {
// add context to the request
localVarRequest = localVarRequest.WithContext(ctx)
// Walk through any authentication.
// Basic HTTP Authentication
if auth, ok := ctx.Value(ContextBasicAuth).(BasicAuth); ok {
localVarRequest.SetBasicAuth(auth.UserName, auth.Password)
}
}
for header, value := range c.cfg.DefaultHeader {
localVarRequest.Header.Add(header, value)
}
return localVarRequest, nil
}
func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err error) {
if len(b) == 0 {
return nil
}
if s, ok := v.(*string); ok {
*s = string(b)
return nil
}
if f, ok := v.(*os.File); ok {
f, err = os.CreateTemp("", "HttpClientFile")
if err != nil {
return
}
_, err = f.Write(b)
if err != nil {
return
}
_, err = f.Seek(0, io.SeekStart)
return
}
if f, ok := v.(**os.File); ok {
*f, err = os.CreateTemp("", "HttpClientFile")
if err != nil {
return
}
_, err = (*f).Write(b)
if err != nil {
return
}
_, err = (*f).Seek(0, io.SeekStart)
return
}
if XmlCheck.MatchString(contentType) {
if err = xml.Unmarshal(b, v); err != nil {
return err
}
return nil
}
if JsonCheck.MatchString(contentType) {
if actualObj, ok := v.(interface{ GetActualInstance() interface{} }); ok { // oneOf, anyOf schemas
if unmarshalObj, ok := actualObj.(interface{ UnmarshalJSON([]byte) error }); ok { // make sure it has UnmarshalJSON defined
if err = unmarshalObj.UnmarshalJSON(b); err != nil {
return err
}
} else {
return errors.New("Unknown type with GetActualInstance but no unmarshalObj.UnmarshalJSON defined")
}
} else if err = json.Unmarshal(b, v); err != nil { // simple model
return err
}
return nil
}
return errors.New("undefined response type")
}
// Add a file to the multipart request
func addFile(w *multipart.Writer, fieldName, path string) error {
file, err := os.Open(filepath.Clean(path))
if err != nil {
return err
}
err = file.Close()
if err != nil {
return err
}
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...)
}
// A wrapper for strict JSON decoding
func newStrictDecoder(data []byte) *json.Decoder {
dec := json.NewDecoder(bytes.NewBuffer(data))
dec.DisallowUnknownFields()
return dec
}
// 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 fp, ok := body.(*os.File); ok {
_, err = bodyBuf.ReadFrom(fp)
} else if b, ok := body.([]byte); ok {
_, err = bodyBuf.Write(b)
} else if s, ok := body.(string); ok {
_, err = bodyBuf.WriteString(s)
} 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) {
var bs []byte
bs, err = xml.Marshal(body)
if err == nil {
bodyBuf.Write(bs)
}
}
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
} else {
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)
}
// GenericOpenAPIError Provides access to the body, error and model on returned errors.
type GenericOpenAPIError struct {
body []byte
error string
model interface{}
}
// Error returns non-empty string if there was an error.
func (e GenericOpenAPIError) Error() string {
return e.error
}
// Body returns the raw bytes of the response
func (e GenericOpenAPIError) Body() []byte {
return e.body
}
// Model returns the unpacked model of the error
func (e GenericOpenAPIError) Model() interface{} {
return e.model
}
// format error message using title and detail when model implements rfc7807
func formatErrorMessage(status string, v interface{}) string {
str := ""
metaValue := reflect.ValueOf(v).Elem()
if metaValue.Kind() == reflect.Struct {
field := metaValue.FieldByName("Title")
if field != (reflect.Value{}) {
str = fmt.Sprintf("%s", field.Interface())
}
field = metaValue.FieldByName("Detail")
if field != (reflect.Value{}) {
str = fmt.Sprintf("%s (%s)", str, field.Interface())
}
}
return strings.TrimSpace(fmt.Sprintf("%s %s", status, str))
}