-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttpx.go
63 lines (54 loc) · 1.19 KB
/
httpx.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
package httpx
import (
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"net/url"
"strconv"
)
func Get(url string, dest interface{}) (err error) {
rawBytes, err := GetRaw(url)
if err != nil {
return err
}
err = json.Unmarshal(rawBytes, dest)
if err != nil {
return errors.New("Unmarshal " + string(rawBytes) + " errMsg: " + err.Error())
}
return nil
}
func GetRaw(url string) ([]byte, error) {
getResp, err := http.Get(url)
if err != nil {
return nil, err
}
defer getResp.Body.Close()
if getResp.StatusCode != 200 {
return nil, errors.New("StatusCode is " + strconv.Itoa(getResp.StatusCode))
}
getRespBody, err := ioutil.ReadAll(getResp.Body)
if err != nil {
return nil, errors.New("read resp body errMsg: " + err.Error())
}
return getRespBody, nil
}
func PostForm(url string, data url.Values, dest interface{}) error {
resp, err := http.PostForm(url, data)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return errors.New("status code is " + strconv.Itoa(resp.StatusCode))
}
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
err = json.Unmarshal(respBody, dest)
if err != nil {
return err
}
return nil
}