-
Notifications
You must be signed in to change notification settings - Fork 152
/
post.go
109 lines (98 loc) · 2.6 KB
/
post.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
package http
import (
"bytes"
"context"
"io"
"io/ioutil"
"net/http"
"net/url"
"github.com/influxdata/flux"
"github.com/influxdata/flux/codes"
"github.com/influxdata/flux/internal/errors"
"github.com/influxdata/flux/iocounter"
"github.com/influxdata/flux/runtime"
"github.com/influxdata/flux/semantic"
"github.com/influxdata/flux/values"
"github.com/opentracing/opentracing-go"
"github.com/opentracing/opentracing-go/log"
)
func init() {
runtime.RegisterPackageValue("http", "post", values.NewFunction(
"post",
runtime.MustLookupBuiltinType("http", "post"),
func(ctx context.Context, args values.Object) (values.Value, error) {
// Get and validate URL
uV, ok := args.Get("url")
if !ok {
return nil, errors.New(codes.Invalid, "missing \"url\" parameter")
}
u, err := url.Parse(uV.Str())
if err != nil {
return nil, err
}
deps := flux.GetDependencies(ctx)
validator, err := deps.URLValidator()
if err != nil {
return nil, err
}
if err := validator.Validate(u); err != nil {
return nil, err
}
// Construct data
var data []byte
dataV, ok := args.Get("data")
if ok {
data = dataV.Bytes()
}
// Construct HTTP request
req, err := http.NewRequest("POST", uV.Str(), bytes.NewReader(data))
if err != nil {
return nil, err
}
// Add headers to request
header, ok := args.Get("headers")
if ok && !header.IsNull() {
var rangeErr error
header.Object().Range(func(k string, v values.Value) {
if v.Type().Nature() == semantic.String {
req.Header.Set(k, v.Str())
} else {
rangeErr = errors.Newf(codes.Invalid, "header value %q must be a string", k)
}
})
if rangeErr != nil {
return nil, rangeErr
}
}
// Perform request
dc, err := deps.HTTPClient()
if err != nil {
return nil, errors.Wrap(err, codes.Aborted, "missing client in http.post")
}
statusCode, err := func(req *http.Request) (int, error) {
s, cctx := opentracing.StartSpanFromContext(ctx, "http.post")
s.SetTag("url", req.URL.String())
defer s.Finish()
req = req.WithContext(cctx)
response, err := dc.Do(req)
if err != nil {
return 0, err
}
wc := iocounter.Writer{Writer: ioutil.Discard}
_, _ = io.Copy(&wc, response.Body)
_ = response.Body.Close()
s.LogFields(
log.Int("statusCode", response.StatusCode),
log.Int64("responseSize", wc.Count()),
)
return response.StatusCode, nil
}(req)
if err != nil {
return nil, err
}
// return status code
return values.NewInt(int64(statusCode)), nil
},
true, // post has side-effects
))
}