/
http_utils.go
109 lines (92 loc) · 2.29 KB
/
http_utils.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
package util
import (
"encoding/json"
"fmt"
"github.com/valyala/fasthttp"
"net/url"
)
type ContentType int
const (
Default ContentType = iota // 开始生成枚举值, 默认为0
Json
)
type RequestOption struct {
Url string
Method string
ReqDto interface{}
Headers map[string]string
ContentType ContentType
}
type ResponseData struct {
Body []byte
Header *fasthttp.ResponseHeader
StatusCode int
}
var client = &fasthttp.Client{}
func GenQueryString(variables map[string]interface{}) string {
params := url.Values{}
for key, value := range variables {
params.Add(key, fmt.Sprintf("%v", value))
}
qs := params.Encode()
return qs
}
func GenFormArgs(variables map[string]interface{}) *fasthttp.Args {
args := &fasthttp.Args{}
for key, value := range variables {
args.Add(key, fmt.Sprintf("%v", value))
}
return args
}
func SendRequest(option *RequestOption) (*ResponseData, error) {
req := fasthttp.AcquireRequest()
defer fasthttp.ReleaseRequest(req)
method := option.Method
reqDto := option.ReqDto
url := option.Url
if method == fasthttp.MethodGet && reqDto != nil {
variables := reqDto.(map[string]interface{})
qs := GenQueryString(variables)
if qs != "" {
url += "?" + qs
}
}
req.SetRequestURI(url)
for key, value := range option.Headers {
req.Header.Add(key, value)
}
req.Header.SetMethod(method)
resp := fasthttp.AcquireResponse()
defer fasthttp.ReleaseResponse(resp)
if option.ContentType == Json {
req.Header.SetContentType("application/json; charset=UTF-8")
bytes, err := json.Marshal(reqDto) //序列化json
if err != nil {
return nil, err
}
req.SetBody(bytes)
} else if method == fasthttp.MethodPost {
req.Header.SetContentType("application/x-www-form-urlencoded; charset=UTF-8")
if reqDto != nil {
variables := reqDto.(map[string]interface{})
bytes := GenFormArgs(variables).QueryString()
req.SetBody(bytes)
}
} else if method == fasthttp.MethodGet {
} else {
return nil, fmt.Errorf("不支持的请求类型")
}
err := client.Do(req, resp)
if err != nil {
return nil, err
}
statusCode := resp.StatusCode()
body := resp.Body()
header := fasthttp.ResponseHeader{}
resp.Header.CopyTo(&header)
return &ResponseData{
Body: body,
Header: &header,
StatusCode: statusCode,
}, nil
}