-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttpclient.go
More file actions
253 lines (217 loc) · 5.03 KB
/
httpclient.go
File metadata and controls
253 lines (217 loc) · 5.03 KB
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
package httpclient
import (
"bytes"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io"
"mime/multipart"
"net/http"
"strconv"
"strings"
"time"
)
type method string
const (
GET = method("GET")
POST = method("POST")
PUT = method("PUT")
DELETE = method("DELETE")
)
type Request struct {
method string
url string
body io.Reader
header map[string]string
query map[string]string
retry int
client *http.Client
response *http.Response
logger Logger
}
type HTTPOption func(r *Request)
// NewHttpRequest 构建一个 Request 对象
func NewHttpRequest(m method, url string, opt ...HTTPOption) *Request {
r := &Request{
method: string(m),
url: url,
client: &http.Client{},
header: make(map[string]string),
query: make(map[string]string),
logger: DefaultLog(),
}
for _, option := range opt {
option(r)
}
return r
}
// With 添加配置项
func (r *Request) With(opt ...HTTPOption) *Request {
for _, option := range opt {
option(r)
}
return r
}
// DoHttpRequest 发送HTTP请求
func (r *Request) DoHttpRequest() ([]byte, error) {
localRetry := 0
do := func() ([]byte, error) {
request, err := http.NewRequest(r.method, r.url, r.body)
if err != nil {
return nil, err
}
for k, v := range r.header {
request.Header.Add(k, v)
}
if r.query != nil && len(r.query) > 0 {
for k, v := range r.query {
query := request.URL.Query()
query.Add(k, v)
request.URL.RawQuery = query.Encode()
}
}
response, err := r.client.Do(request)
r.response = response
if err != nil {
return nil, err
}
resp, err := io.ReadAll(response.Body)
defer response.Body.Close()
if err != nil {
return nil, err
}
if response.StatusCode >= 200 && response.StatusCode < 300 {
return resp, nil
}
return resp, errors.New(fmt.Sprintf("status code = %d", response.StatusCode))
}
for {
res, err := do()
if err == nil {
return res, nil
}
if localRetry == r.retry {
return res, err
}
localRetry++
r.logger.Error(fmt.Sprintf("请求[%s]失败,进行%d次重试...", r.url, localRetry))
time.Sleep(time.Duration(200*localRetry) * time.Millisecond)
}
}
// GetResponse 获取返回
func (r *Request) GetResponse() *http.Response {
return r.response
}
// GetClient 获取原始 http 客户端
func (r *Request) GetClient() *http.Client {
return r.client
}
// WithClient 设置 http 客户端
func WithClient(c *http.Client) HTTPOption {
return func(r *Request) {
r.client = c
}
}
// WithLog 设置日志输出
func WithLog(logger Logger) HTTPOption {
return func(r *Request) {
r.logger = logger
}
}
// WithQuery 设置 GET 请求参数
func WithQuery(query map[string]string) HTTPOption {
return func(r *Request) {
r.query = query
}
}
// WithTimeout 设置请求超时
func WithTimeout(d time.Duration) HTTPOption {
return func(r *Request) {
r.client.Timeout = d
}
}
// WithRetry 设置重试次数 默认不重试
func WithRetry(retryTime int) HTTPOption {
return func(r *Request) {
r.retry = retryTime
}
}
// WithRawBody 设置自定义请求结构
func WithRawBody(body io.Reader) HTTPOption {
return func(r *Request) {
r.body = body
}
}
// WithJson 设置请求结构为 JSON
func WithJson(body any) HTTPOption {
return func(r *Request) {
marshal, _ := json.Marshal(body)
r.body = bytes.NewBuffer(marshal)
r.header["Content-Type"] = "application/json;charset=UTF-8"
}
}
// WithFromData 设置请求结构为 from-urlencoded
func WithFromData(body map[string]any) HTTPOption {
return func(r *Request) {
r.body = strings.NewReader(Map2Str(body))
r.header["Content-Type"] = "application/x-www-form-urlencoded;charset=UTF-8"
}
}
// WithHeader 添加请求头
func WithHeader(key, val string) HTTPOption {
return func(r *Request) {
r.header[key] = val
}
}
// WithMultipartFrom 设置请求结构为 form-data
func WithMultipartFrom(fromData map[string]string, files ...*UploadFile) HTTPOption {
body := &bytes.Buffer{}
newWriter := multipart.NewWriter(body)
// 文件处理
if files != nil {
for _, file := range files {
formFile, _ := newWriter.CreateFormFile(file.Field, file.FileName)
_, _ = io.Copy(formFile, file.File)
}
}
// 普通字段处理
if fromData != nil && len(fromData) > 0 {
for k, v := range fromData {
_ = newWriter.WriteField(k, v)
}
}
_ = newWriter.Close()
return func(r *Request) {
r.body = body
r.header["Content-Type"] = newWriter.FormDataContentType()
}
}
func WithOutTlsVerify() HTTPOption {
return func(r *Request) {
r.client.Transport = &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}
}
}
func Map2Str(m map[string]any) string {
var strArr []string
for k, v := range m {
strArr = append(strArr, k+"="+ConvertString(v))
}
return strings.Join(strArr, "&")
}
func ConvertString(value any) string {
switch value := value.(type) {
case string:
return value
case int:
return strconv.Itoa(value)
case int64:
return strconv.Itoa(int(value))
case json.Number:
return value.String()
case float64:
return strconv.FormatFloat(value, 'f', -1, 64)
default:
return ""
}
}