-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
118 lines (99 loc) · 2.07 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 do
import (
"encoding/json"
"encoding/xml"
"fmt"
"io"
"net/http"
"time"
)
type (
CodeChecker func(code int) error
)
func CodeIs200(code int) error {
if code != http.StatusOK {
return fmt.Errorf("bad http code: %d", code)
}
return nil
}
type (
ResultExtractor[R any] func(data []byte) (R, error)
)
func RawExtractor(data []byte) ([]byte, error) {
return data, nil
}
func JSONExtractor[R any](data []byte) (R, error) {
var r R
if err := json.Unmarshal(data, &r); err != nil {
return r, err
}
return r, nil
}
func XMLExtractor[R any](data []byte) (R, error) {
var r R
if err := xml.Unmarshal(data, &r); err != nil {
return r, err
}
return r, nil
}
// SendHTTPRequest send http request and get result of type R. If you want to got resp header, the R should implement RespHeaderExtractor interface.
func SendHTTPRequest[R any](
client *http.Client,
method string,
link string,
body io.Reader,
header http.Header,
codeChecker CodeChecker,
extractResult ResultExtractor[R],
) (R, error) {
var r R
if method == "" || link == "" {
return r, fmt.Errorf("bad param: method or link is empty")
}
req, err := http.NewRequest(method, link, body)
if err != nil {
return r, err
}
for k, v := range header {
for _, vv := range v {
req.Header.Set(k, vv)
}
}
if client == nil {
client = &http.Client{
Timeout: 10 * time.Second,
}
}
resp, err := client.Do(req)
if err != nil {
return r, err
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
return r, err
}
if codeChecker == nil {
codeChecker = CodeIs200
}
err = codeChecker(resp.StatusCode)
if err != nil {
return r, fmt.Errorf("check code failed: %v, data: %s", err, data)
}
if extractResult == nil {
extractResult = JSONExtractor[R]
}
r, err = extractResult(data)
if err != nil {
return r, fmt.Errorf("extract result failed: %v, data: %s", err, data)
}
// with header
h := resp.Header
if e, ok := any(r).(RespHeaderExtractor); ok && e != nil {
e.Extract(h)
}
return r, nil
}
type RespHeaderExtractor interface {
Extract(h http.Header)
}