-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathhttp.go
1042 lines (1005 loc) · 26.4 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
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package lib
import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"net/url"
"reflect"
"strings"
"github.com/google/cel-go/cel"
"github.com/google/cel-go/checker/decls"
"github.com/google/cel-go/common/types"
"github.com/google/cel-go/common/types/ref"
"github.com/google/cel-go/common/types/traits"
"github.com/google/cel-go/interpreter/functions"
"golang.org/x/time/rate"
expr "google.golang.org/genproto/googleapis/api/expr/v1alpha1"
)
// HTTP returns a cel.EnvOption to configure extended functions for HTTP
// requests. Requests and responses are returned as maps corresponding to
// the Go http.Request and http.Response structs. The client and limit parameters
// will be used for the requests and API rate limiting. If client is nil
// the http.DefaultClient will be used and if limit is nil an non-limiting
// rate.Limiter will be used.
//
// HEAD
//
// head performs a HEAD method request and returns the result:
//
// head(<string>) -> <map<string,dyn>>
//
// Example:
//
// head('http://www.example.com/') // returns {"Body": "", "Close": false,
//
//
// GET
//
// get performs a GET method request and returns the result:
//
// get(<string>) -> <map<string,dyn>>
//
// Example:
//
// get('http://www.example.com/') // returns {"Body": "PCFkb2N0e...
//
//
// GET Request
//
// get returns a GET method request:
//
// get(<string>) -> <map<string,dyn>>
//
// Example:
//
// get_request('http://www.example.com/')
//
// will return:
//
// {
// "Close": false,
// "ContentLength": 0,
// "Header": {},
// "Host": "www.example.com",
// "Method": "GET",
// "Proto": "HTTP/1.1",
// "ProtoMajor": 1,
// "ProtoMinor": 1,
// "URL": "http://www.example.com/"
// }
//
//
// POST
//
// post performs a POST method request and returns the result:
//
// post(<string>, <string>, <bytes>) -> <map<string,dyn>>
// post(<string>, <string>, <string>) -> <map<string,dyn>>
//
// Example:
//
// post("http://www.example.com/", "text/plain", "test") // returns {"Body": "PCFkb2N0e...
//
//
// POST Request
//
// post_request returns a POST method request:
//
// post_request(<string>, <string>, <bytes>) -> <map<string,dyn>>
// post_request(<string>, <string>, <string>) -> <map<string,dyn>>
//
// Example:
//
// post("http://www.example.com/", "text/plain", "test")
//
// will return:
//
// {
// "Body": "test",
// "Close": false,
// "ContentLength": 4,
// "Header": {
// "Content-Type": [
// "text/plain"
// ]
// },
// "Host": "www.example.com",
// "Method": "POST",
// "Proto": "HTTP/1.1",
// "ProtoMajor": 1,
// "ProtoMinor": 1,
// "URL": "http://www.example.com/"
// }
//
//
// Request
//
// request returns a user-defined method request:
//
// request(<string>, <string>, <string>, <bytes>) -> <map<string,dyn>>
// request(<string>, <string>, <string>, <string>) -> <map<string,dyn>>
//
// Example:
//
// request("GET", "http://www.example.com/").with({"Header":{
// "Authorization": "Basic "+string(base64("username:password")),
// }})
//
// will return:
//
// {
// "Close": false,
// "ContentLength": 0,
// "Header": {
// "Authorization": "Basic dXNlcm5hbWU6cGFzc3dvcmQ="
// },
// "Host": "www.example.com",
// "Method": "GET",
// "Proto": "HTTP/1.1",
// "ProtoMajor": 1,
// "ProtoMinor": 1,
// "URL": "http://www.example.com/"
// }
//
//
// Do Request
//
// do_request executes an HTTP request:
//
// <map<string,dyn>>.do_request() -> <map<string,dyn>>
//
// Example:
//
// get_request("http://www.example.com/").do_request() // returns {"Body": "PCFkb2N0e...
//
//
// Parse URL
//
// parse_url returns a map holding the details of the parsed URL corresponding
// to the Go url.URL struct:
//
// <string>.parse_url() -> <map<string,dyn>>
//
// Example:
//
// "https://pkg.go.dev/net/url#URL".parse_url()
//
// will return:
//
// {
// "ForceQuery": false,
// "Fragment": "URL",
// "Host": "pkg.go.dev",
// "Opaque": "",
// "Path": "/net/url",
// "RawFragment": "",
// "RawPath": "",
// "RawQuery": "",
// "Scheme": "https",
// "User": null
// }
//
//
// Format URL
//
// format_url returns string corresponding to the URL map that is the receiver:
//
// <map<string,dyn>>.format_url() -> <string>
//
// Example:
//
// "https://pkg.go.dev/net/url#URL".parse_url().with_replace({"Host": "godoc.org"}).format_url()
//
// will return:
//
// "https://godoc.org/net/url#URL"
//
//
// Parse Query
//
// parse_query returns a map holding the details of the parsed query corresponding
// to the Go url.Values map:
//
// <string>.parse_query() -> <map<string,<list<string>>>
//
// Example:
//
// "page=1&line=25".parse_url()
//
// will return:
//
// {
// "line": ["25"],
// "page": ["1"]
// }
//
//
// Format Query
//
// format_query returns string corresponding to the query map that is the receiver:
//
// <map<string,<list<string>>>.format_query() -> <string>
//
// Example:
//
// "page=1&line=25".parse_query().with_replace({"page":[string(2)]}).format_query()
//
// will return:
//
// line=25&page=2"
//
func HTTP(client *http.Client, limit *rate.Limiter) cel.EnvOption {
return HTTPWithContext(context.Background(), client, limit)
}
// HTTP returns a cel.EnvOption to configure extended functions for HTTP
// requests that include a context.Context in network requests.
func HTTPWithContext(ctx context.Context, client *http.Client, limit *rate.Limiter) cel.EnvOption {
if client == nil {
client = http.DefaultClient
}
if limit == nil {
limit = rate.NewLimiter(rate.Inf, 0)
}
return cel.Lib(httpLib{
client: client,
limit: limit,
ctx: ctx,
})
}
type httpLib struct {
client *http.Client
limit *rate.Limiter
ctx context.Context
}
func (httpLib) CompileOptions() []cel.EnvOption {
return []cel.EnvOption{
cel.Declarations(
decls.NewFunction("head",
decls.NewOverload(
"head_string",
[]*expr.Type{decls.String},
decls.NewMapType(decls.String, decls.Dyn),
),
),
decls.NewFunction("get",
decls.NewOverload(
"get_string",
[]*expr.Type{decls.String},
decls.NewMapType(decls.String, decls.Dyn),
),
),
decls.NewFunction("get_request",
decls.NewOverload(
"get_request_string",
[]*expr.Type{decls.String},
decls.NewMapType(decls.String, decls.Dyn),
),
),
decls.NewFunction("post",
decls.NewOverload(
"post_string_string_bytes",
[]*expr.Type{decls.String, decls.String, decls.Bytes},
decls.NewMapType(decls.String, decls.Dyn),
),
decls.NewOverload(
"post_string_string_string",
[]*expr.Type{decls.String, decls.String, decls.String},
decls.NewMapType(decls.String, decls.Dyn),
),
),
decls.NewFunction("post_request",
decls.NewOverload(
"post_request_string_string_bytes",
[]*expr.Type{decls.String, decls.String, decls.Bytes},
decls.NewMapType(decls.String, decls.Dyn),
),
decls.NewOverload(
"post_request_string_string_string",
[]*expr.Type{decls.String, decls.String, decls.String},
decls.NewMapType(decls.String, decls.Dyn),
),
),
decls.NewFunction("request",
decls.NewOverload(
"request_string_string",
[]*expr.Type{decls.String, decls.String},
decls.NewMapType(decls.String, decls.Dyn),
),
decls.NewOverload(
"request_string_string_bytes",
[]*expr.Type{decls.String, decls.String, decls.Bytes},
decls.NewMapType(decls.String, decls.Dyn),
),
decls.NewOverload(
"request_string_string_string",
[]*expr.Type{decls.String, decls.String, decls.String},
decls.NewMapType(decls.String, decls.Dyn),
),
),
decls.NewFunction("do_request",
decls.NewInstanceOverload(
"map_do_request",
[]*expr.Type{decls.NewMapType(decls.String, decls.Dyn)},
decls.NewMapType(decls.String, decls.Dyn),
),
),
decls.NewFunction("parse_url",
decls.NewInstanceOverload(
"string_parse_url",
[]*expr.Type{decls.String},
decls.NewMapType(decls.String, decls.Dyn),
),
),
decls.NewFunction("format_url",
decls.NewInstanceOverload(
"map_format_url",
[]*expr.Type{decls.NewMapType(decls.String, decls.Dyn)},
decls.String,
),
),
decls.NewFunction("parse_query",
decls.NewInstanceOverload(
"string_parse_query",
[]*expr.Type{decls.String},
decls.NewMapType(decls.String, decls.NewListType(decls.String)),
),
),
decls.NewFunction("format_query",
decls.NewInstanceOverload(
"map_format_query",
[]*expr.Type{decls.NewMapType(decls.String, decls.NewListType(decls.String))},
decls.String,
),
),
),
}
}
func (l httpLib) ProgramOptions() []cel.ProgramOption {
return []cel.ProgramOption{
cel.Functions(
&functions.Overload{
Operator: "head_string",
Unary: l.doHead,
},
),
cel.Functions(
&functions.Overload{
Operator: "get_string",
Unary: l.doGet,
},
),
cel.Functions(
&functions.Overload{
Operator: "get_request_string",
Unary: newGetRequest,
},
),
cel.Functions(
&functions.Overload{
Operator: "post_string_string_bytes",
Function: l.doPost,
},
&functions.Overload{
Operator: "post_string_string_string",
Function: l.doPost,
},
),
cel.Functions(
&functions.Overload{
Operator: "post_request_string_string_bytes",
Function: newPostRequest,
},
&functions.Overload{
Operator: "post_request_string_string_string",
Function: newPostRequest,
},
),
cel.Functions(
&functions.Overload{
Operator: "request_string_string",
Binary: newRequest,
},
&functions.Overload{
Operator: "request_string_string_bytes",
Function: newRequestBody,
},
&functions.Overload{
Operator: "request_string_string_string",
Function: newRequestBody,
},
),
cel.Functions(
&functions.Overload{
Operator: "map_do_request",
Unary: l.doRequest,
},
),
cel.Functions(
&functions.Overload{
Operator: "string_parse_url",
Unary: parseURL,
},
),
cel.Functions(
&functions.Overload{
Operator: "map_format_url",
Unary: formatURL,
},
),
cel.Functions(
&functions.Overload{
Operator: "string_parse_query",
Unary: parseQuery,
},
),
cel.Functions(
&functions.Overload{
Operator: "map_format_query",
Unary: formatQuery,
},
),
}
}
func (l httpLib) doHead(arg ref.Val) ref.Val {
url, ok := arg.(types.String)
if !ok {
return types.ValOrErr(url, "no such overload for head")
}
err := l.limit.Wait(context.TODO())
if err != nil {
return types.NewErr("%s", err)
}
resp, err := l.head(url)
if err != nil {
return types.NewErr("%s", err)
}
rm, err := respToMap(resp)
if err != nil {
return types.NewErr("%s", err)
}
return types.DefaultTypeAdapter.NativeToValue(rm)
}
func (l httpLib) head(url types.String) (*http.Response, error) {
req, err := http.NewRequestWithContext(l.ctx, http.MethodHead, string(url), nil)
if err != nil {
return nil, err
}
return l.client.Do(req)
}
func (l httpLib) doGet(arg ref.Val) ref.Val {
url, ok := arg.(types.String)
if !ok {
return types.ValOrErr(url, "no such overload for get")
}
err := l.limit.Wait(context.TODO())
if err != nil {
return types.NewErr("%s", err)
}
resp, err := l.get(url)
if err != nil {
return types.NewErr("%s", err)
}
rm, err := respToMap(resp)
if err != nil {
return types.NewErr("%s", err)
}
return types.DefaultTypeAdapter.NativeToValue(rm)
}
func (l httpLib) get(url types.String) (*http.Response, error) {
req, err := http.NewRequestWithContext(l.ctx, http.MethodGet, string(url), nil)
if err != nil {
return nil, err
}
return l.client.Do(req)
}
func newGetRequest(url ref.Val) ref.Val {
return newRequestBody(types.String("GET"), url)
}
func (l httpLib) doPost(args ...ref.Val) ref.Val {
if len(args) != 3 {
return types.NewErr("no such overload for post")
}
url, ok := args[0].(types.String)
if !ok {
return types.ValOrErr(url, "no such overload for request")
}
content, ok := args[1].(types.String)
if !ok {
return types.ValOrErr(content, "no such overload for request")
}
var body io.Reader
switch text := args[2].(type) {
case types.Bytes:
if len(text) != 0 {
body = bytes.NewReader(text)
}
case types.String:
if text != "" {
body = strings.NewReader(string(text))
}
default:
return types.NewErr("invalid type for post body: %s", text.Type())
}
err := l.limit.Wait(context.TODO())
if err != nil {
return types.NewErr("%s", err)
}
resp, err := l.post(url, content, body)
if err != nil {
return types.NewErr("%s", err)
}
rm, err := respToMap(resp)
if err != nil {
return types.NewErr("%s", err)
}
return types.DefaultTypeAdapter.NativeToValue(rm)
}
func (l httpLib) post(url, content types.String, body io.Reader) (*http.Response, error) {
req, err := http.NewRequestWithContext(l.ctx, http.MethodPost, string(url), body)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", string(content))
return l.client.Do(req)
}
func newPostRequest(args ...ref.Val) ref.Val {
if len(args) != 3 {
return types.NewErr("no such overload for post request")
}
content, ok := args[1].(types.String)
if !ok {
return types.ValOrErr(content, "no such overload for request")
}
url := args[0]
body := args[2]
req, err := makeRequestBody(types.String("POST"), url, body)
if err != nil {
return err
}
h, ok := req["Header"]
if !ok {
h = make(http.Header)
req["Header"] = h
}
h.(http.Header).Set("Content-Type", string(content))
return types.DefaultTypeAdapter.NativeToValue(req)
}
func newRequest(method, url ref.Val) ref.Val {
return newRequestBody(method, url)
}
func newRequestBody(args ...ref.Val) ref.Val {
req, err := makeRequestBody(args...)
if err != nil {
return err
}
return types.DefaultTypeAdapter.NativeToValue(req)
}
func makeRequestBody(args ...ref.Val) (map[string]interface{}, ref.Val) {
if len(args) < 2 {
return nil, types.NewErr("no such overload for request")
}
method, ok := args[0].(types.String)
if !ok {
return nil, types.ValOrErr(method, "no such overload for request")
}
url, ok := args[1].(types.String)
if !ok {
return nil, types.ValOrErr(method, "no such overload for request")
}
var (
body ref.Val
bodyReader io.Reader
)
if len(args) == 3 {
body = args[2]
switch body := body.(type) {
case types.Bytes:
if len(body) != 0 {
bodyReader = bytes.NewReader(body)
}
case types.String:
if body != "" {
bodyReader = strings.NewReader(string(body))
}
default:
return nil, types.NewErr("invalid type for request body: %s", body.Type())
}
}
req, err := http.NewRequest(string(method), string(url), bodyReader)
if err != nil {
return nil, types.NewErr("%s", err)
}
reqMap, err := reqToMap(req, url, body)
if err != nil {
return nil, types.NewErr("%s", err)
}
return reqMap, nil
}
func reqToMap(req *http.Request, url, body ref.Val) (map[string]interface{}, error) {
rm := map[string]interface{}{
"Method": req.Method,
"URL": url,
"Proto": req.Proto,
"ProtoMajor": req.ProtoMajor,
"ProtoMinor": req.ProtoMinor,
"Header": req.Header,
"ContentLength": req.ContentLength,
"Close": req.Close,
"Host": req.Host,
}
if req.RequestURI != "" {
rm["RequestURI"] = req.RequestURI
}
if body != nil {
rm["Body"] = body
}
if req.TransferEncoding != nil {
rm["TransferEncoding"] = req.TransferEncoding
}
if req.Trailer != nil {
rm["Trailer"] = req.Trailer
}
if req.Response != nil {
resp, err := respToMap(req.Response)
if err != nil {
return nil, err
}
rm["Response"] = resp
}
return rm, nil
}
func respToMap(resp *http.Response) (map[string]interface{}, error) {
rm := map[string]interface{}{
"Status": resp.Status,
"StatusCode": resp.StatusCode,
"Proto": resp.Proto,
"ProtoMajor": resp.ProtoMajor,
"ProtoMinor": resp.ProtoMinor,
"Header": resp.Header,
"ContentLength": resp.ContentLength,
"Close": resp.Close,
"Uncompressed": resp.Uncompressed,
}
var buf bytes.Buffer
_, err := io.Copy(&buf, resp.Body)
resp.Body.Close()
if err != nil {
return nil, err
}
rm["Body"] = buf.Bytes()
if resp.TransferEncoding != nil {
rm["TransferEncoding"] = resp.TransferEncoding
}
if resp.Trailer != nil {
rm["Trailer"] = resp.Trailer
}
if resp.Request != nil {
req, err := reqToMap(resp.Request, types.String(resp.Request.URL.String()), nil)
if err != nil {
return nil, err
}
rm["Request"] = req
}
return rm, nil
}
func (l httpLib) doRequest(arg ref.Val) ref.Val {
request, ok := arg.(traits.Mapper)
if !ok {
return types.ValOrErr(request, "no such overload for do_request")
}
reqm, err := request.ConvertToNative(reflectMapStringAnyType)
if err != nil {
return types.NewErr("%s", err)
}
req, err := mapToReq(reqm.(map[string]interface{}))
if err != nil {
return types.NewErr("%s", err)
}
// Recover the context lost during serialisation to JSON.
req = req.WithContext(l.ctx)
err = l.limit.Wait(l.ctx)
if err != nil {
return types.NewErr("%s", err)
}
resp, err := l.client.Do(req)
if err != nil {
return types.NewErr("%s", err)
}
respm, err := respToMap(resp)
if err != nil {
return types.NewErr("%s", err)
}
return types.DefaultTypeAdapter.NativeToValue(respm)
}
func mapToReq(rm map[string]interface{}) (*http.Request, error) {
if rm == nil {
return nil, nil
}
req := &http.Request{}
err := mapConv(reflect.ValueOf(req).Elem(), rm)
return req, err
}
func mapToResp(rm map[string]interface{}) (*http.Response, error) {
if rm == nil {
return nil, nil
}
resp := &http.Response{}
err := mapConv(reflect.ValueOf(resp).Elem(), rm)
return resp, err
}
func mapConv(dst reflect.Value, src map[string]interface{}) error {
rt := dst.Type()
for i := 0; i < dst.NumField(); i++ {
ft := rt.Field(i)
if !ft.IsExported() {
continue
}
v, ok := src[ft.Name]
if !ok {
continue
}
conv, ok := convFuncs[ft.Type.String()]
if !ok {
continue
}
val, err := conv(reflect.ValueOf(v))
if err != nil {
return err
}
dst.Field(i).Set(val)
}
return nil
}
var convFuncs = map[string]func(val reflect.Value) (reflect.Value, error){
"int": func(val reflect.Value) (reflect.Value, error) { return val.Convert(reflectIntType), nil },
"int64": func(val reflect.Value) (reflect.Value, error) { return val.Convert(reflectInt64Type), nil },
"bool": func(val reflect.Value) (reflect.Value, error) { return val.Convert(reflectBoolType), nil },
"string": func(val reflect.Value) (reflect.Value, error) { return val.Convert(reflectStringType), nil },
"[]string": makeStrings,
"io.ReadCloser": makeBody,
"*url.URL": makeURL,
"http.Header": makeMapStrings,
"url.Values": makeMapStrings,
"*multipart.Form": func(val reflect.Value) (reflect.Value, error) { panic("TODO") },
"*tls.ConnectionState": func(val reflect.Value) (reflect.Value, error) { panic("TODO") },
// These should pass through without this being implemented, but mark them.
"*http.Request": func(val reflect.Value) (reflect.Value, error) { panic("REPORT BUG: http.Request") },
"*http.Response": func(val reflect.Value) (reflect.Value, error) { panic("REPORT BUG: http.Response") },
}
func makeMapStrings(val reflect.Value) (reflect.Value, error) {
iface := val.Interface()
switch iface := iface.(type) {
case http.Header:
return reflect.ValueOf(iface), nil
case url.Values:
return reflect.ValueOf(iface), nil
case map[string][]string:
return reflect.ValueOf(iface), nil
case map[ref.Val]ref.Val:
val := types.DefaultTypeAdapter.NativeToValue(iface)
v, err := val.ConvertToNative(reflectMapStringStringSliceType)
if err != nil {
return reflect.Value{}, err
}
return reflect.ValueOf(v), nil
case ref.Val:
v, err := iface.ConvertToNative(reflectMapStringStringSliceType)
if err != nil {
return reflect.Value{}, err
}
return reflect.ValueOf(v.(map[string][]string)), nil
default:
return reflect.Value{}, fmt.Errorf("invalid type: %T", iface)
}
}
func makeStrings(val reflect.Value) (reflect.Value, error) {
iface := val.Interface()
switch iface := iface.(type) {
case []string:
return reflect.ValueOf(iface), nil
case []types.String:
dst := make([]string, len(iface))
for i, s := range iface {
dst[i] = string(s)
}
return reflect.ValueOf(dst), nil
case ref.Val:
v, err := iface.ConvertToNative(reflectStringSliceType)
if err != nil {
return reflect.Value{}, err
}
return reflect.ValueOf(v), nil
case []ref.Val:
dst := make([]string, len(iface))
for i, s := range iface {
v, err := s.ConvertToNative(reflectStringType)
if err != nil {
return reflect.Value{}, err
}
dst[i] = v.(string)
}
return reflect.ValueOf(dst), nil
default:
return reflect.Value{}, fmt.Errorf("invalid type: %T", iface)
}
}
func makeBody(val reflect.Value) (reflect.Value, error) {
var r io.Reader
switch val.Kind() {
case reflect.String:
r = strings.NewReader(val.String())
case reflect.Slice:
if !val.CanConvert(reflectByteSliceType) {
return reflect.Value{}, fmt.Errorf("invalid type: %s", val.Type())
}
r = bytes.NewReader(val.Bytes())
default:
return reflect.Value{}, fmt.Errorf("invalid type: %s", val.Type())
}
return reflect.ValueOf(io.NopCloser(r)), nil
}
func makeURL(val reflect.Value) (reflect.Value, error) {
if val.Kind() != reflect.String {
return reflect.Value{}, fmt.Errorf("invalid type: %s", val.Type())
}
u, err := url.Parse(val.String())
if err != nil {
return reflect.Value{}, err
}
return reflect.ValueOf(u), nil
}
func parseURL(arg ref.Val) ref.Val {
addr, ok := arg.(types.String)
if !ok {
return types.ValOrErr(addr, "no such overload for request")
}
u, err := url.Parse(string(addr))
if err != nil {
return types.NewErr("%s", err)
}
var user interface{}
if u.User != nil {
password, passwordSet := u.User.Password()
user = map[string]interface{}{
"Username": u.User.Username(),
"Password": password,
"PasswordSet": passwordSet,
}
}
return types.NewStringInterfaceMap(types.DefaultTypeAdapter, map[string]interface{}{
"Scheme": u.Scheme,
"Opaque": u.Opaque,
"User": user,
"Host": u.Host,
"Path": u.Path,
"RawPath": u.RawPath,
"ForceQuery": u.ForceQuery,
"RawQuery": u.RawQuery,
"Fragment": u.Fragment,
"RawFragment": u.RawFragment,
})
}
func formatURL(arg ref.Val) ref.Val {
urlMap, ok := arg.(traits.Mapper)
if !ok {
return types.ValOrErr(urlMap, "no such overload")
}
v, err := urlMap.ConvertToNative(reflectMapStringAnyType)
if err != nil {
return types.NewErr("no such overload for format_url: %v", err)
}
m, ok := v.(map[string]interface{})
if !ok {
// This should never happen.
return types.NewErr("unexpected type for url map: %T", v)
}
u := url.URL{
Scheme: maybeStringLookup(m, "Scheme"),
Opaque: maybeStringLookup(m, "Opaque"),
Host: maybeStringLookup(m, "Host"),
Path: maybeStringLookup(m, "Path"),
RawPath: maybeStringLookup(m, "RawPath"),
ForceQuery: maybeBoolLookup(m, "ForceQuery"),
RawQuery: maybeStringLookup(m, "RawQuery"),
Fragment: maybeStringLookup(m, "Fragment"),
RawFragment: maybeStringLookup(m, "RawFragment"),
}
user, ok := urlMap.Find(types.String("User"))
if ok {
switch user := user.(type) {
case nil:
case traits.Mapper:
var username types.String
un, ok := user.Find(types.String("Username"))
if ok {
username, ok = un.(types.String)
if !ok {
return types.NewErr("invalid type for username: %s", un.Type())
}
}
if user.Get(types.String("PasswordSet")) == types.True {
var password types.String
pw, ok := user.Find(types.String("Password"))
if ok {
password, ok = pw.(types.String)
if !ok {
return types.NewErr("invalid type for password: %s", pw.Type())
}
}
u.User = url.UserPassword(string(username), string(password))
} else {
u.User = url.User(string(username))
}
default:
if user != types.NullValue {
return types.NewErr("unsupported type: %T", user)
}
}
}
return types.String(u.String())
}
// maybeStringLookup returns a string from m[key] if it is present and the
// empty string if not. It panics is m[key] is not a string.
func maybeStringLookup(m map[string]interface{}, key string) string {
v, ok := m[key]
if !ok {
return ""
}
return v.(string)