-
Notifications
You must be signed in to change notification settings - Fork 3
/
http.go
118 lines (98 loc) · 2.29 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
package step
import (
"bytes"
"encoding/json"
"io"
"io/ioutil"
"net/http"
"time"
)
type HttpStep struct {
DefaultTimeout time.Duration `json:"default_timeout"`
DefaultMethod string `json:"default_method"`
}
func UnmarshalHttpStep(reader io.Reader) (HttpStep, error) {
var step HttpStep
err := json.NewDecoder(reader).Decode(&step)
return step, err
}
func NewHTTP(defaultTimeout time.Duration, defaultMethod string) HttpStep {
return HttpStep{
DefaultTimeout: defaultTimeout,
DefaultMethod: defaultMethod,
}
}
type HttpStepInput struct {
Timeout time.Duration `json:"timeout"`
Method string `json:"method"`
URL string `json:"url"`
Body map[string]interface{} `json:"body"`
Header http.Header `json:"header"`
}
type HttpStepOutput struct {
StatusCode int `json:"status_code"`
Header http.Header `json:"header"`
Body map[string]interface{} `json:"body"`
}
func (h HttpStep) Invoke(reader io.Reader, writer io.Writer) error {
var config HttpStepInput
err := json.NewDecoder(reader).Decode(&config)
if err != nil {
return err
}
client := h.client(config)
req, err := h.request(config)
if err != nil {
return err
}
res, err := client.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
var out HttpStepOutput
out.StatusCode = res.StatusCode
out.Header = res.Header
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return err
}
err = json.Unmarshal(body, &out.Body)
if err != nil {
return err
}
return json.NewEncoder(writer).Encode(out)
}
func (h *HttpStep) client(config HttpStepInput) http.Client {
timeout := h.DefaultTimeout
if config.Timeout != 0 {
timeout = config.Timeout
}
return http.Client{
Timeout: timeout,
}
}
func (h *HttpStep) request(config HttpStepInput) (*http.Request, error) {
method := h.DefaultMethod
if config.Method != "" {
method = config.Method
}
url := config.URL
var body io.Reader
if config.Body != nil {
buf := &bytes.Buffer{}
err := json.NewEncoder(buf).Encode(config.Body)
if err != nil {
return nil, err
}
body = buf
}
req, err := http.NewRequest(method, url, body)
if err != nil {
return nil, err
}
if config.Header != nil {
req.Header = config.Header
}
return req, nil
}