-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
59 lines (49 loc) · 962 Bytes
/
client.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
package insight
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
)
type Client struct {
url string
httpClient *http.Client
}
func NewClient(apiURL string) *Client {
return &Client{
url: apiURL,
httpClient: &http.Client{},
}
}
func (c *Client) doRequest(path string, params url.Values, res interface{}) error {
if path[0] != '/' {
path = "/" + path
}
urlParams := ""
if params != nil {
urlParams = "?" + params.Encode()
}
reqURL := fmt.Sprintf("%s%s%s", c.url, path, urlParams)
req, err := http.NewRequest("GET", reqURL, nil)
if err != nil {
return err
}
resp, err := c.httpClient.Do(req)
if err != nil {
return err
}
if resp.StatusCode != 200 {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
return fmt.Errorf("Error %d: %s", resp.StatusCode, body)
}
dec := json.NewDecoder(resp.Body)
err = dec.Decode(res)
if err != nil {
return err
}
return nil
}