-
Notifications
You must be signed in to change notification settings - Fork 6
/
http.go
827 lines (656 loc) · 18.5 KB
/
http.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
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
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
// Copyright (c) 2022 AccelByte Inc. All Rights Reserved.
// This is licensed software from AccelByte Inc, for limitations
// and restrictions contact your company contract manager.
package utils
import (
"bytes"
"context"
"fmt"
"io"
"log"
"mime"
"mime/multipart"
"net/http"
"net/http/httputil"
"net/textproto"
"net/url"
"os"
"path"
"path/filepath"
"strings"
"sync"
"time"
oar "github.com/go-openapi/runtime"
oarLogger "github.com/go-openapi/runtime/logger"
oarYaml "github.com/go-openapi/runtime/yamlpc"
oaStrFmt "github.com/go-openapi/strfmt"
)
//#region Constants
const (
HeaderContentDisposition = "Content-Disposition"
)
//#endregion Constants
//#region Vars
var (
DefaultTimeout = 30 * time.Second
)
//#endregion Vars
//#region Interfaces
type PreSendABRequestFunc func(r *ABRequest) (*ABRequest, error)
type PreSendHttpRequestFunc func(r *http.Request) (*http.Request, error)
// ClientTransport Implements runtime.ClientTransport
type ClientTransport interface {
GetRoundTripper() http.RoundTripper
GetPreSendABRequestFunc() PreSendABRequestFunc
SetPreSendABRequestFunc(PreSendABRequestFunc) error
GetPreSendHttpRequestFunc() PreSendHttpRequestFunc
SetPreSendHttpRequestFunc(PreSendHttpRequestFunc) error
oar.ClientTransport // for Submit(*ClientOperation) (interface{}, error)
}
//#endregion Interfaces
//#region Structs
//#region ABClientTransport
// ABClientTransport Implements utils.ClientTransport
type ABClientTransport struct {
DefaultMediaType string
DefaultAuthentication oar.ClientAuthInfoWriter
Consumers map[string]oar.Consumer
Producers map[string]oar.Producer
Transport http.RoundTripper
Jar http.CookieJar
Host string
BasePath string
Schemes []string
Formats oaStrFmt.Registry
Context context.Context
Debug bool
Logger oarLogger.Logger
clientOnce *sync.Once
client *http.Client
preSendABRequestFunc PreSendABRequestFunc
preSendHttpRequestFunc PreSendHttpRequestFunc
}
//#region ABClientTransport.New
func NewABClientTransport(host, basePath string, schemes []string) *ABClientTransport {
var clientTransport ABClientTransport
clientTransport.DefaultMediaType = oar.JSONMime
clientTransport.DefaultAuthentication = nil
clientTransport.Consumers = map[string]oar.Consumer{
oar.YAMLMime: oarYaml.YAMLConsumer(),
oar.JSONMime: oar.JSONConsumer(),
oar.XMLMime: oar.XMLConsumer(),
oar.TextMime: oar.TextConsumer(),
oar.HTMLMime: oar.TextConsumer(),
oar.CSVMime: oar.CSVConsumer(),
oar.DefaultMime: oar.ByteStreamConsumer(),
}
clientTransport.Producers = map[string]oar.Producer{
oar.YAMLMime: oarYaml.YAMLProducer(),
oar.JSONMime: oar.JSONProducer(),
oar.XMLMime: oar.XMLProducer(),
oar.TextMime: oar.TextProducer(),
oar.HTMLMime: oar.TextProducer(),
oar.CSVMime: oar.CSVProducer(),
oar.DefaultMime: oar.ByteStreamProducer(),
}
clientTransport.Transport = http.DefaultTransport
clientTransport.Jar = nil
clientTransport.Host = host
clientTransport.BasePath = basePath
if !strings.HasPrefix(clientTransport.BasePath, "/") {
clientTransport.BasePath = "/" + clientTransport.BasePath
}
if len(schemes) > 0 {
clientTransport.Schemes = schemes
}
clientTransport.Formats = nil
clientTransport.Context = context.Background()
clientTransport.Debug = oarLogger.DebugEnabled()
clientTransport.Logger = oarLogger.StandardLogger{}
clientTransport.clientOnce = new(sync.Once)
return &clientTransport
}
func NewABClientTransportWithHttpClient(host, basePath string, schemes []string, httpClient *http.Client) *ABClientTransport {
clientTransport := NewABClientTransport(host, basePath, schemes)
if httpClient != nil {
clientTransport.clientOnce.Do(func() {
clientTransport.client = httpClient
})
}
return clientTransport
}
//#endregion ABClientTransport.New
//#region ABClientTransport.Utils
func (ct *ABClientTransport) NewHttpClient() *http.Client {
return &http.Client{
Transport: ct.Transport,
Jar: ct.Jar,
}
}
func (ct *ABClientTransport) PickScheme(schemes []string) string {
if scheme := SelectScheme(ct.Schemes); scheme != "" {
return scheme
}
if scheme := SelectScheme(schemes); scheme != "" {
return scheme
}
return "http"
}
//#endregion ABClientTransport.Utils
//#region ABClientTransport (utils.ClientTransport)
func (ct *ABClientTransport) GetRoundTripper() http.RoundTripper {
return ct.Transport
}
func (ct *ABClientTransport) GetPreSendABRequestFunc() PreSendABRequestFunc {
return ct.preSendABRequestFunc
}
func (ct *ABClientTransport) SetPreSendABequestFunc(requestFunc PreSendABRequestFunc) error {
ct.preSendABRequestFunc = requestFunc
return nil
}
func (ct *ABClientTransport) GetPreSendHttpRequestFunc() PreSendHttpRequestFunc {
return ct.preSendHttpRequestFunc
}
func (ct *ABClientTransport) SetPreSendHttpRequestFunc(requestFunc PreSendHttpRequestFunc) error {
ct.preSendHttpRequestFunc = requestFunc
return nil
}
func (ct *ABClientTransport) Submit(clientOperation *oar.ClientOperation) (interface{}, error) {
readResponse := clientOperation.Reader
auth := clientOperation.AuthInfo
abRequest, err := NewABRequestFromClientOperation(clientOperation)
if err != nil {
return nil, err
}
if auth == nil && ct.DefaultAuthentication != nil {
auth = ct.DefaultAuthentication
}
cmt := ct.DefaultMediaType
for _, mediaType := range clientOperation.ConsumesMediaTypes {
// Pick first non-empty media type.
if mediaType != "" {
cmt = mediaType
break
}
}
if _, ok := ct.Producers[cmt]; !ok &&
cmt != oar.MultipartFormMime &&
cmt != oar.URLencodedFormMime {
return nil, fmt.Errorf("none of the producers: %v registered - try %s", ct.Producers, cmt)
}
if ct.preSendABRequestFunc != nil {
abRequest, err = ct.preSendABRequestFunc(abRequest)
if err != nil {
return nil, err
}
}
timeout := abRequest.Timeout
httpRequest, err := NewHttpRequestFromABRequest(
abRequest,
cmt,
ct.BasePath,
ct.Producers,
ct.Formats,
auth,
)
if err != nil {
return nil, err
}
httpRequest.URL.Scheme = ct.PickScheme(clientOperation.Schemes)
httpRequest.URL.Host = ct.Host
httpRequest.Host = ct.Host
ct.clientOnce.Do(func() {
ct.client = ct.NewHttpClient()
})
if ct.Debug {
debugBytes, debugErr := httputil.DumpRequestOut(httpRequest, true)
if debugErr != nil {
return nil, debugErr
}
ct.Logger.Debugf("%s\n", string(debugBytes))
}
var hasTimeout bool
opCtx := clientOperation.Context
if opCtx == nil {
opCtx = ct.Context
} else {
hasTimeout = true
}
if opCtx == nil {
opCtx = context.Background()
}
var ctx context.Context
var cancel context.CancelFunc
if hasTimeout {
ctx, cancel = context.WithCancel(opCtx)
} else {
ctx, cancel = context.WithTimeout(opCtx, timeout)
}
defer cancel()
client := clientOperation.Client
if client == nil {
client = ct.client
}
httpRequest = httpRequest.WithContext(ctx)
if ct.preSendHttpRequestFunc != nil {
httpRequest, err = ct.preSendHttpRequestFunc(httpRequest)
if err != nil {
return nil, err
}
}
httpResponse, err := client.Do(httpRequest)
if err != nil {
return nil, err
}
defer func(Body io.ReadCloser) {
_ = Body.Close()
}(httpResponse.Body)
contentType := httpResponse.Header.Get(oar.HeaderContentType)
if contentType == "" {
contentType = ct.DefaultMediaType
}
if ct.Debug {
printBody := true
if contentType == oar.DefaultMime {
printBody = false
}
debugBytes, debugErr := httputil.DumpResponse(httpResponse, printBody)
if debugErr != nil {
return nil, debugErr
}
ct.Logger.Debugf("%s\n", string(debugBytes))
}
mediaType, _, err := mime.ParseMediaType(contentType)
if err != nil {
return nil, fmt.Errorf("parse content type: %s", err)
}
consumer, ok := ct.Consumers[mediaType]
if !ok {
if consumer, ok = ct.Consumers["*/*"]; !ok {
return nil, fmt.Errorf("no consumer: %q", contentType)
}
}
return readResponse.ReadResponse(NewABResponseFromHttpResponse(httpResponse), consumer)
}
//#endregion ABClientTransport (utils.ClientTransport)
//#endregion ABClientTransport
//#region ABRequest
// ABRequest Implements runtime.ClientRequest
type ABRequest struct {
PathPattern string
Method string
Writer oar.ClientRequestWriter
PathParams map[string]string
Header http.Header
Query url.Values
FormFields url.Values
FileFields map[string][]oar.NamedReadCloser
Payload interface{}
Timeout time.Duration
Buf *bytes.Buffer
GetBodyFunc func(r *ABRequest) []byte
}
//#region ABRequest.New
func NewABRequestFromClientOperation(clientOperation *oar.ClientOperation) (*ABRequest, error) {
abRequest := ABRequest{
PathPattern: clientOperation.PathPattern,
Method: clientOperation.Method,
Writer: clientOperation.Params,
Header: make(http.Header),
Query: make(url.Values),
Timeout: DefaultTimeout,
GetBodyFunc: GetRequestBuffer,
}
var accept []string
accept = append(accept, clientOperation.ProducesMediaTypes...)
if err := abRequest.SetHeaderParam(oar.HeaderAccept, accept...); err != nil {
return nil, err
}
return &abRequest, nil
}
//#endregion ABRequest.New
//#region ABRequest.Utils
func NewHttpRequestFromABRequest(
req *ABRequest,
mediaType string,
basePath string,
producers map[string]oar.Producer,
registry oaStrFmt.Registry,
auth oar.ClientAuthInfoWriter,
) (*http.Request, error) {
if err := req.Writer.WriteToRequest(req, registry); err != nil {
return nil, err
}
// NOTE(go-openapi):
// Our body must be an io.Reader.
// When we create the http.Request, if we pass it a
// bytes.Buffer then it will wrap it in an io.ReadCloser
// and set the content length automatically.
var body io.Reader
var pr *io.PipeReader
var pw *io.PipeWriter
req.Buf = bytes.NewBuffer(nil)
if req.Payload != nil || len(req.FormFields) > 0 || len(req.FileFields) > 0 {
body = req.Buf
if IsMultipart(req, mediaType) {
pr, pw = io.Pipe()
body = pr
}
}
if IsFormType(req) {
if !IsMultipart(req, mediaType) {
req.Header.Set(oar.HeaderContentType, mediaType)
formString := req.FormFields.Encode()
req.Buf.WriteString(formString)
goto DoneChoosingBodySource
}
mp := multipart.NewWriter(pw)
mpContentType := MangleContentType(mediaType, mp.Boundary())
req.Header.Set(oar.HeaderContentType, mpContentType)
go func() {
defer func() {
_ = mp.Close()
_ = pw.Close()
}()
for fn, v := range req.FormFields {
for _, vi := range v {
if err := mp.WriteField(fn, vi); err != nil {
_ = pw.CloseWithError(err)
log.Println(err)
}
}
}
defer func() {
for _, ff := range req.FileFields {
for _, ffi := range ff {
_ = ffi.Close()
}
}
}()
for fn, f := range req.FileFields {
for _, fi := range f {
buf := bytes.NewBuffer([]byte{})
_, err := io.Copy(buf, fi)
if err != nil {
_ = pw.CloseWithError(err)
log.Println(err)
}
fileBytes := buf.Bytes()
fileContentType := http.DetectContentType(fileBytes)
newFi := oar.NamedReader(fi.Name(), buf)
contentDisposition := fmt.Sprintf(
`form-data; name="%s"; filename="%s"`,
EscapeQuotes(fn),
EscapeQuotes(filepath.Base(fi.Name())))
mimeHeader := make(textproto.MIMEHeader)
mimeHeader.Set(HeaderContentDisposition, contentDisposition)
mimeHeader.Set(oar.HeaderContentType, fileContentType)
multiPartWriter, err := mp.CreatePart(mimeHeader)
if err != nil {
_ = pw.CloseWithError(err)
log.Println(err)
} else if _, err := io.Copy(multiPartWriter, newFi); err != nil {
_ = pw.CloseWithError(err)
log.Println(err)
}
}
}
}()
goto DoneChoosingBodySource
}
if req.Payload != nil {
req.Header.Set(oar.HeaderContentType, mediaType)
if payloadReader, ok := req.Payload.(io.ReadCloser); ok {
body = payloadReader
goto DoneChoosingBodySource
}
if payloadReader, ok := req.Payload.(io.Reader); ok {
body = payloadReader
goto DoneChoosingBodySource
}
producer := producers[mediaType]
if err := producer.Produce(req.Buf, req.Payload); err != nil {
return nil, err
}
}
DoneChoosingBodySource:
if oar.CanHaveBody(req.Method) && body == nil && req.Header.Get(oar.HeaderContentType) == "" {
req.Header.Set(oar.HeaderContentType, mediaType)
}
if auth != nil {
// NOTE(go-openapi):
// If we're not using req.buf as our http.Request's body,
// either the payload is an io.Reader or io.ReadCloser,
// or we're doing a multipart form/file.
//
// In those cases, if the AuthenticateRequest call asks for the body,
// we must read it into a buffer and provide that, then use that buffer
// as the body of our http.Request.
//
// This is done in-line with the GetBody() request rather than ahead
// of time, because there's no way to know if the AuthenticateRequest
// will even ask for the body of the request.
//
// If for some reason the copy fails, there's no way to return that
// error to the GetBody() call, so return it afterwards.
//
// An error from the copy action is prioritized over any error
// from the AuthenticateRequest call, because the misread
// body may have interfered with the auth.
var copyErr error
if buf, ok := body.(*bytes.Buffer); body != nil && (!ok || buf != req.Buf) {
var copied bool
req.GetBodyFunc = func(r *ABRequest) []byte {
if copied {
return GetRequestBuffer(r)
}
defer func() {
copied = true
}()
if _, copyErr = io.Copy(r.Buf, body); copyErr != nil {
return nil
}
if closer, ok := body.(io.ReadCloser); ok {
if copyErr = closer.Close(); copyErr != nil {
return nil
}
}
body = r.Buf
return GetRequestBuffer(r)
}
}
authErr := auth.AuthenticateRequest(req, registry)
if copyErr != nil {
return nil, fmt.Errorf("error retrieving the response body: %v", copyErr)
}
if authErr != nil {
return nil, authErr
}
}
var reinstateSlash bool
if req.PathPattern != "" &&
req.PathPattern != "/" &&
req.PathPattern[len(req.PathPattern)-1] == '/' {
reinstateSlash = true
}
urlPath := path.Join(basePath, req.PathPattern)
for k, v := range req.PathParams {
urlPath = strings.Replace(urlPath, "{"+k+"}", url.PathEscape(v), -1)
}
if reinstateSlash {
urlPath = urlPath + "/"
}
httpRequest, err := http.NewRequest(req.Method, urlPath, body)
if err != nil {
return nil, err
}
httpRequest.URL.RawQuery = req.Query.Encode()
httpRequest.Header = req.Header
httpRequest.GetBody = func() (io.ReadCloser, error) {
if readCloser, ok := body.(io.ReadCloser); ok {
return readCloser, nil
}
return nil, nil
}
return httpRequest, nil
}
func IsFormType(r *ABRequest) bool {
return len(r.FormFields) > 0 || len(r.FileFields) > 0
}
func IsMultipart(r *ABRequest, mediaType string) bool {
if len(r.FileFields) > 0 {
return true
}
return oar.MultipartFormMime == mediaType
}
func GetRequestBuffer(r *ABRequest) []byte {
if r.Buf == nil {
return nil
}
return r.Buf.Bytes()
}
func MangleContentType(mediaType, boundary string) string {
if strings.ToLower(mediaType) == oar.URLencodedFormMime {
return fmt.Sprintf("%s; boundary=%s", mediaType, boundary)
}
return "multipart/form-data; boundary=" + boundary
}
//#endregion ABRequest.Utils
//#region ABRequest (runtime.ClientRequest)
func (r *ABRequest) GetBody() []byte {
return r.GetBodyFunc(r)
}
func (r *ABRequest) GetBodyParam() interface{} {
return r.Payload
}
func (r *ABRequest) GetFileParam() map[string][]oar.NamedReadCloser {
return r.FileFields
}
func (r *ABRequest) GetHeaderParams() http.Header {
return r.Header
}
func (r *ABRequest) GetMethod() string {
return r.Method
}
func (r *ABRequest) GetQueryParams() url.Values {
var result = make(url.Values)
for key, value := range r.Query {
result[key] = append([]string{}, value...)
}
return result
}
func (r *ABRequest) GetPath() string {
pathStr := r.PathPattern
for k, v := range r.PathParams {
pathStr = strings.Replace(pathStr, "{"+k+"}", v, -1)
}
return pathStr
}
func (r *ABRequest) SetBodyParam(payload interface{}) error {
r.Payload = payload
return nil
}
func (r *ABRequest) SetFileParam(name string, files ...oar.NamedReadCloser) error {
for _, file := range files {
if actualFile, ok := file.(*os.File); ok {
fi, err := os.Stat(actualFile.Name())
if err != nil {
return err
}
if fi.IsDir() {
return fmt.Errorf("%q is a directory, only files are supported", file.Name())
}
}
}
if r.FileFields == nil {
r.FileFields = make(map[string][]oar.NamedReadCloser)
}
r.FileFields[name] = files
if r.FormFields == nil {
r.FormFields = make(url.Values)
}
return nil
}
func (r *ABRequest) SetFormParam(name string, values ...string) error {
if r.FormFields == nil {
r.FormFields = make(url.Values)
}
r.FormFields[name] = values
return nil
}
func (r *ABRequest) SetHeaderParam(name string, values ...string) error {
if r.Header == nil {
r.Header = make(http.Header)
}
r.Header[http.CanonicalHeaderKey(name)] = values
return nil
}
func (r *ABRequest) SetPathParam(name string, value string) error {
if r.PathParams == nil {
r.PathParams = make(map[string]string)
}
r.PathParams[name] = value
return nil
}
func (r *ABRequest) SetQueryParam(name string, values ...string) error {
if r.Query == nil {
r.Query = make(url.Values)
}
r.Query[name] = values
return nil
}
func (r *ABRequest) SetTimeout(timeout time.Duration) error {
r.Timeout = timeout
return nil
}
//#endregion ABRequest (runtime.ClientRequest)
//#endregion ABRequest
//#region ABResponse
// ABResponse Implements runtime.ClientResponse
type ABResponse struct {
response *http.Response
}
func NewABResponseFromHttpResponse(httpResponse *http.Response) ABResponse {
return ABResponse{response: httpResponse}
}
//#region ABResponse (runtime.ClientResponse)
func (r ABResponse) Body() io.ReadCloser {
return r.response.Body
}
func (r ABResponse) Code() int {
return r.response.StatusCode
}
func (r ABResponse) GetHeader(name string) string {
return r.response.Header.Get(name)
}
func (r ABResponse) Message() string {
return r.response.Status
}
func (r ABResponse) GetHeaders(name string) []string {
return r.response.Header.Values(name)
}
//#endregion ABResponse (runtime.ClientResponse)
//#endregion ABResponse
//#endregion Structs
//#region Utils
func EscapeQuotes(s string) string {
return strings.NewReplacer("\\", "\\\\", `"`, "\\\"").Replace(s)
}
func SelectScheme(schemes []string) string {
schemeLen := len(schemes)
if schemeLen == 0 {
return ""
}
scheme := schemes[0]
if scheme == "http" &&
schemeLen > 1 {
for _, otherScheme := range schemes {
if otherScheme == "https" {
scheme = otherScheme
break
}
}
}
return scheme
}
//#endregion Utils