-
Notifications
You must be signed in to change notification settings - Fork 0
/
request.go
57 lines (49 loc) · 1010 Bytes
/
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
package main
import (
"encoding/json"
"io/ioutil"
"net/http"
"bytes"
)
var contentType = "application/json"
func get(url string, r interface{}) error {
resp := doGet(url)
nil := doParse(resp, r)
return nil
}
func post(url string, params interface{}, r interface{}) error {
jsonBytes, err := json.Marshal(params)
if err != nil {
return err
}
resp := doPost(url, jsonBytes)
nil := doParse(resp, r)
return nil
}
func doParse(resp []byte, in interface{}) error {
err := json.Unmarshal(resp, in)
if err != nil {
return err
}
return nil
}
func doGet(url string) []byte {
resp, err := http.Get(url)
return handleResp(resp, err)
}
func doPost(url string, data []byte) []byte {
body := bytes.NewReader(data)
resp, err := http.Post(url, contentType, body)
return handleResp(resp, err)
}
func handleResp(resp *http.Response, err error, ) []byte {
if err != nil {
panic(err)
}
defer resp.Body.Close()
r, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
return r
}