-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequest.go
More file actions
108 lines (91 loc) · 2.49 KB
/
request.go
File metadata and controls
108 lines (91 loc) · 2.49 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
package utils
import (
"io/ioutil"
"net/http"
"net/url"
"strings"
)
func NewRequest() *Request {
return &Request{}
}
type Request struct {
}
// http get request
func (utils *Request) Get(queryUrl string, queryValues map[string]string, headerValues map[string]string) (body string, code int, err error) {
req, err := http.NewRequest("GET", utils.QueryBuilder(queryUrl, queryValues), nil)
if err != nil {
return
}
if (headerValues != nil) && (len(headerValues) > 0) {
for key, value := range headerValues {
req.Header.Set(key, value)
}
}
client := &http.Client{}
resp, err := client.Do(req)
code = resp.StatusCode
defer resp.Body.Close()
bodyByte, err := ioutil.ReadAll(resp.Body)
if err != nil {
return
}
return string(bodyByte), code, nil
}
// http post request
func (utils *Request) HttpPost(queryUrl string, queryValues map[string]string, headerValues map[string]string) (body string, code int, err error) {
if !strings.Contains(queryUrl, "?") {
queryUrl += "?"
}
queryString := ""
for queryKey, queryValue := range queryValues {
queryString = queryString + "&" + queryKey + "=" + url.QueryEscape(queryValue)
}
queryString = strings.Replace(queryString, "&", "", 1)
req, err := http.NewRequest("POST", queryUrl, strings.NewReader(queryString))
if err != nil {
return
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
if (headerValues != nil) && (len(headerValues) > 0) {
for key, value := range headerValues {
req.Header.Set(key, value)
}
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return
}
code = resp.StatusCode
defer resp.Body.Close()
bodyByte, err := ioutil.ReadAll(resp.Body)
if err != nil {
return
}
return string(bodyByte), code, nil
}
// build query params
func (utils *Request) QueryBuilder(queryUrl string, queryValues map[string]string) string {
if !strings.Contains(queryUrl, "?") {
queryUrl += "?"
}
queryString := ""
for queryKey, queryValue := range queryValues {
queryString = queryString + "&" + queryKey + "=" + url.QueryEscape(queryValue)
}
queryString = strings.Replace(queryString, "&", "", 1)
queryUrl += queryString
return queryUrl
}
// parse params(name=nick&pass=123)
func (utils *Request) ParseString(params string) map[string]string {
paramsMap := map[string]string{}
for _, param := range strings.Split(params, "&") {
if !strings.Contains(param, "=") {
continue
}
paramList := strings.Split(param, "=")
paramsMap[paramList[0]] = paramList[1]
}
return paramsMap
}