forked from ungerik/go-rest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.go
42 lines (39 loc) · 1020 Bytes
/
util.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
package rest
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
// GetJSON sends a HTTP GET request to addr and
// unmarshalles the JSON response to out.
func GetJSON(addr string, out interface{}) error {
response, err := http.Get(addr)
if err != nil {
return err
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return err
}
return json.Unmarshal(body, out)
}
// GetJSONStrict sends a HTTP GET request to addr and
// unmarshalles the JSON response to out.
// Returns an error if Content-Type is not application/json.
func GetJSONStrict(addr string, out interface{}) error {
response, err := http.Get(addr)
if err != nil {
return err
}
if ct := response.Header.Get("Content-Type"); ct != "application/json" {
return fmt.Errorf("GetJSONStrict expected Content-Type 'application/json', but got '%s'", ct)
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return err
}
return json.Unmarshal(body, out)
}