-
Notifications
You must be signed in to change notification settings - Fork 59
/
rest.go
45 lines (37 loc) · 879 Bytes
/
rest.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
package main
import (
"bytes"
"net/http"
"encoding/json"
"github.com/juju/errors"
"io/ioutil"
)
//call http url and get json, then decode to objptr
func httpCall(objPtr interface{}, url string, method string, arg interface{}) error {
client := &http.Client{Transport: http.DefaultTransport}
rw := &bytes.Buffer{}
if arg != nil {
buf, err := json.Marshal(arg)
if err != nil {
return errors.Trace(err)
}
rw.Write(buf)
}
req, err := http.NewRequest(method, url, rw)
if err != nil {
return errors.Trace(err)
}
resp, err := client.Do(req)
if err != nil {
return errors.Trace(err)
}
defer resp.Body.Close()
if resp.StatusCode/100 != 2 {
msg, _ := ioutil.ReadAll(resp.Body)
return errors.Errorf("error: %d, message: %s", resp.StatusCode, string(msg))
}
if objPtr != nil {
return json.NewDecoder(resp.Body).Decode(objPtr)
}
return nil
}