-
Notifications
You must be signed in to change notification settings - Fork 0
/
httpx.go
235 lines (195 loc) · 5.95 KB
/
httpx.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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
package httpx
import (
"bytes"
"encoding/json"
"io"
"net"
"net/http"
"strings"
"time"
"errors"
"github.com/madlabx/pkgx/errno"
"github.com/madlabx/pkgx/log"
)
func GetRealIp(req *http.Request) string {
hip := req.Header.Get("X-Forwarded-For")
if hip != "" {
idx := strings.Index(hip, ",")
if idx > 0 {
return hip[:idx]
}
return hip
}
hip = req.Header.Get("X-Real-IP")
if hip != "" {
return hip
}
ip, _, _ := net.SplitHostPort(req.RemoteAddr)
return ip
}
var defaultClient = &Client{cli: http.DefaultClient}
func ResetDefaultClient(hc *Client) {
defaultClient = hc
}
func HttpGetBody(url string) (*http.Response, []byte, error) {
return requestBytesForBody(defaultClient, "GET", url, nil, true)
}
func HttpGet(url string) (*http.Response, error) {
return requestBytes(defaultClient, "GET", url, nil)
}
func HttpPostBody(url string, body interface{}) (*http.Response, []byte, error) {
b, err := json.Marshal(body)
if err != nil {
log.Errorf("Parse json failed, url: %s, obj: %#v", url, body)
return nil, nil, ErrorResp(http.StatusBadRequest, errno.ECODE_BAD_REQUEST_PARAM, err)
}
return requestBytesForBody(defaultClient, "POST", url, b, true)
}
type Client struct {
cli *http.Client
}
func (hc *Client) clone() *Client {
newRawClient := *hc.cli
return &Client{cli: &newRawClient}
}
func (hc *Client) HttpPost(url string, body interface{}) (*http.Response, error) {
return httpPostInternal(hc, url, body)
}
func (hc *Client) HttpGetBody(url string) (*http.Response, []byte, error) {
return requestBytesForBody(hc, "GET", url, nil, true)
}
func (hc *Client) HttpGet(url string) (*http.Response, error) {
return requestBytes(hc, "GET", url, nil)
}
func (hc *Client) WithTimeout(timeout int) *Client {
hc.cli.Timeout = time.Second * time.Duration(timeout)
return hc
}
func WithTimeout(timeout int) *Client {
return defaultClient.clone().WithTimeout(timeout)
}
func HttpPost(url string, body interface{}) (*http.Response, error) {
b, err := json.Marshal(body)
if err != nil {
log.Errorf("Parse json failed, url: %s, obj: %#v", url, body)
return nil, ErrorResp(http.StatusBadRequest, errno.ECODE_BAD_REQUEST_PARAM, err)
}
return requestBytes(
defaultClient,
"POST",
url,
b)
}
func httpPostInternal(cli *Client, url string, body interface{}) (*http.Response, error) {
b, err := json.Marshal(body)
if err != nil {
log.Errorf("Parse json failed, url: %s, obj: %#v", url, body)
return nil, ErrorResp(http.StatusBadRequest, errno.ECODE_BAD_REQUEST_PARAM, err)
}
return requestBytes(cli, "POST", url, b)
}
func requestBytes(cli *Client, method, url string, bodyBytes []byte) (*http.Response, error) {
resp, _, err := requestBytesForBody(cli, method, url, bodyBytes, false)
return resp, err
}
func requestBytesForBody(hc *Client, method, requrl string, bodyBytes []byte, wantBody bool) (*http.Response, []byte, error) {
req, err := http.NewRequest(method, requrl, bytes.NewReader(bodyBytes))
if err != nil {
log.Errorf("failed to build request, err:%#v", err.Error())
return nil, nil, err
}
if method == "POST" {
req.Header.Set("Content-Type", "application/json")
}
req.Header.Set("Connection", "close")
rsp, err := hc.cli.Do(req)
if err != nil {
log.Errorf("failed to send request, err:%#v", err.Error())
return nil, nil, Wrap(err)
}
defer func() {
if rsp != nil {
_ = rsp.Body.Close()
}
}()
if rsp.StatusCode != http.StatusOK && rsp.StatusCode != http.StatusCreated {
body, err := io.ReadAll(rsp.Body)
if err != nil {
log.Errorf("read body err, err:%v, response:%v", err.Error(), rsp)
return nil, nil, err
}
err = errors.New(rsp.Status)
return rsp, body, err
}
if wantBody {
body, err := io.ReadAll(rsp.Body)
if err != nil {
log.Errorf("read body err, %v", err.Error())
return nil, nil, err
}
return rsp, body, err
}
return rsp, nil, err
}
func requestBytesForBodyNormal(method, reqUrl string, bodyBytes []byte, wantBody bool) (*http.Response, []byte, error) {
client := &http.Client{
Timeout: 20 * time.Second,
}
req, err := http.NewRequest(method, reqUrl, bytes.NewReader(bodyBytes))
if err != nil {
log.Errorf("failed to build request, err:%#v", err.Error())
return nil, nil, err
}
if method == "POST" {
req.Header.Set("Content-Type", "application/json")
}
req.Header.Set("Connection", "close")
rsp, err := client.Do(req)
if err != nil {
log.Errorf("failed to send request, err:%#v", err.Error())
return nil, nil, Wrap(err)
}
defer func() {
if rsp != nil {
_ = rsp.Body.Close()
}
}()
if rsp.StatusCode != http.StatusOK && rsp.StatusCode != http.StatusCreated {
body, err := io.ReadAll(rsp.Body)
if err != nil {
log.Errorf("read body err, err:%v, response:%v", err.Error(), rsp)
return nil, nil, ErrStrResp(rsp.StatusCode, errno.ECODE_FAILED_HTTP_REQUEST, "Failed to parse response body")
}
//log.Errorf("Got not 200 response[%#v], body[%v]", rsp, string(body))
var newStatusError JsonResponse
err = json.Unmarshal(body, &newStatusError)
if err != nil {
log.Errorf("read body err, err:%v, response:%v", err.Error(), rsp)
return nil, nil, ErrStrResp(rsp.StatusCode, errno.ECODE_FAILED_HTTP_REQUEST, "Failed to parse error information: "+string(body))
}
newStatusError.Status = rsp.StatusCode
if *newStatusError.CodeInt == errno.ECODE_SUCCESS {
*newStatusError.CodeInt = errno.ECODE_FAILED_HTTP_REQUEST
*newStatusError.Message = string(body)
}
//log.Errorf("err:%v", newStatusError)
return rsp, body, &newStatusError
}
if wantBody {
body, err := io.ReadAll(rsp.Body)
if err != nil {
log.Errorf("read body err, %v", err.Error())
return nil, nil, ErrStrResp(rsp.StatusCode, errno.ECODE_FAILED_HTTP_REQUEST, "Failed to parse response body")
}
return rsp, body, err
}
return rsp, nil, err
}
func ResponseToMap(body []byte) (map[string]interface{}, error) {
var set map[string]interface{}
if err := json.Unmarshal(body, &set); err != nil {
log.Errorf("Unmarshal err, %v", err.Error())
return nil, err
}
return set, nil
}