/
http_client.go
executable file
·103 lines (80 loc) · 1.84 KB
/
http_client.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
package services
import (
"bytes"
"context"
"encoding/json"
"io/ioutil"
"net/http"
"strings"
)
type marshalClient func(interface{}) string
func jsonMarshal(v interface{}) string {
buff, err := json.Marshal(v)
if err != nil {
return ""
}
return string(buff)
}
var marshalClientStruct marshalClient = jsonMarshal
type result struct {
Error string `json:"error,omitempty"`
StatusCode int `json:"statusCode,omitempty"`
Headers map[string]string `json:"headers,omitempty"`
Body string `json:"body,omitempty"`
}
type Client interface {
Request(context.Context, *RequestInput) *ResponseOutput
}
type HttpClient struct {
http *http.Client
}
func NewHttpClient(c *http.Client) *HttpClient {
return &HttpClient{c}
}
func (hc *HttpClient) Request(
ctx context.Context,
ri *RequestInput) *ResponseOutput {
req, err := http.NewRequestWithContext(
ctx,
ri.Method,
ri.URL,
bytes.NewBufferString(ri.Body))
if err != nil {
return &ResponseOutput{
Status: ScheduleStatusFailed,
Result: marshalClientStruct(result{Error: err.Error()}),
}
}
for k, v := range ri.Headers {
req.Header.Set(k, v)
}
res, err := hc.http.Do(req)
if err != nil {
return &ResponseOutput{
Status: ScheduleStatusFailed,
Result: marshalClientStruct(result{Error: err.Error()}),
}
}
defer func() {
_ = res.Body.Close()
}()
headers := make(map[string]string)
for k, v := range res.Header {
headers[k] = strings.Join(v, ";")
}
body, _ := ioutil.ReadAll(res.Body)
var status string
if res.StatusCode >= 200 && res.StatusCode < 300 {
status = ScheduleStatusSucceeded
} else {
status = ScheduleStatusFailed
}
return &ResponseOutput{
Status: status,
Result: marshalClientStruct(result{
StatusCode: res.StatusCode,
Headers: headers,
Body: string(body),
}),
}
}