-
Notifications
You must be signed in to change notification settings - Fork 0
/
netdef.go
70 lines (63 loc) · 1.35 KB
/
netdef.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
// +build !js
package gophernet
import (
"io"
"io/ioutil"
"net/http"
"net/url"
)
func (c *Client) get(urlStr string, params Values) ([]byte, error) {
urlParsed, err := url.Parse(urlStr)
if err != nil {
return nil, err
}
queriesInitial := urlParsed.Query()
for key, arr := range params {
for _, val := range arr {
queriesInitial.Add(key, val)
}
}
urlParsed.RawQuery = queriesInitial.Encode()
urlStr = urlParsed.String()
client := &http.Client{}
req, err := http.NewRequest("GET", urlStr, nil)
if err != nil {
return nil, err
}
for key, list := range c.Header {
for _, val := range list {
req.Header[key] = append(req.Header[key], val)
}
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return body, nil
}
func (c *Client) post(url string, contentType string, body io.Reader) ([]byte, error) {
client := &http.Client{}
req, err := http.NewRequest("POST", url, body)
if err != nil {
return nil, err
}
for key, list := range c.Header {
for _, val := range list {
req.Header[key] = append(req.Header[key], val)
}
}
req.Header.Set("Content-Type", contentType)
resp, err := client.Do(req)
if err != nil {
return nil, err
}
output, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return output, nil
}