-
Notifications
You must be signed in to change notification settings - Fork 0
/
rest.go
49 lines (44 loc) · 897 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
46
47
48
49
package restgo
import (
"bytes"
"encoding/json"
"errors"
"io/ioutil"
"net/http"
)
func Get(url string, resp interface{}) error {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return err
}
return do(req, resp)
}
func Post(url string, req, resp interface{}) error {
d, err := json.Marshal(req)
if err != nil {
return err
}
body := bytes.NewBuffer(d)
request, err := http.NewRequest("POST", url, body)
if err != nil {
return err
}
request.Header.Set("Content-Type", "application/json")
return do(request, resp)
}
func do(req *http.Request, resp interface{}) error {
res, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
data, err := ioutil.ReadAll(res.Body)
if err != nil {
return err
}
err = json.Unmarshal(data, resp)
if res.StatusCode != http.StatusOK {
return errors.New(res.Status)
}
return err
}