forked from phachon/wmqx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequest.go
83 lines (72 loc) · 1.88 KB
/
request.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
package main
import (
"strings"
"net/url"
"net/http"
"io/ioutil"
)
func httpGet(queryUrl string, queryValues map[string]string, headerValues map[string]string) (body []byte, 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)
queryUrl += queryString
req, err := http.NewRequest("GET", queryUrl, 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)
if err != nil {
return
}
code = resp.StatusCode
defer resp.Body.Close()
bodyByte, err := ioutil.ReadAll(resp.Body)
if err != nil {
return
}
return bodyByte, code, nil
}
// http post request
func httpPost(queryUrl string, queryValues map[string]string, headerValues map[string]string) (body []byte, 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 bodyByte, code, nil
}