-
Notifications
You must be signed in to change notification settings - Fork 0
/
do.go
108 lines (84 loc) · 2.31 KB
/
do.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
package rest
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
type Method string
const (
GET Method = "GET"
POST Method = "POST"
PUT Method = "PUT"
DELETE Method = "DELETE"
)
const minStatusCode = 399
type Header map[string]string
// Body must be a map, struct or string.
type Body any
// Result must be a map, or a pointer to a struct or string
type Result any
type Response struct {
Raw *http.Response
Request *http.Request
Data []byte
RespBodyCloseErr error
}
func Do(method Method, url string, header Header, body Body, result Result) (*Response, error) {
return DoWithClient(http.DefaultClient, method, url, header, body, result)
}
func DoWithClient(client *http.Client, method Method, url string, header Header, body Body, result Result) (*Response, error) {
if client == nil {
return nil, fmt.Errorf("rest: client is nil")
}
bd, err := json.Marshal(body)
if err != nil {
return nil, fmt.Errorf("reset: marshal body to bytes, err: %w", err)
}
req, err := http.NewRequest(string(method), url, bytes.NewReader(bd))
if err != nil {
return nil, fmt.Errorf("rest: can not new request, err: %w", err)
}
if header != nil {
for k, v := range header {
req.Header.Set(k, v)
}
}
r := &Response{
Request: req,
}
r.Raw, err = client.Do(req)
if err != nil {
return r, err
}
defer func() {
r.RespBodyCloseErr = r.Raw.Body.Close()
}()
if r.Raw.StatusCode > minStatusCode {
return r, fmt.Errorf("rest: status %v > %v", r.Raw.StatusCode, minStatusCode)
}
r.Data, err = io.ReadAll(r.Raw.Body)
if err != nil {
return r, fmt.Errorf("rest: can not read response body, err: %w", err)
}
if result != nil && r.Data != nil {
err = json.Unmarshal(r.Data, result)
if err != nil {
return r, fmt.Errorf("rest: can not unmarshal response data, err: %w", err)
}
}
return r, nil
}
func Get(url string, header Header, result Result) (*Response, error) {
return Do(GET, url, header, nil, result)
}
func Post(url string, header Header, body Body, result Result) (*Response, error) {
return Do(POST, url, header, body, result)
}
func Put(url string, header Header, body Body, result Result) (*Response, error) {
return Do(PUT, url, header, body, result)
}
func Delete(url string, header Header, result Result) (*Response, error) {
return Do(DELETE, url, header, nil, result)
}