-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrequest.go
More file actions
72 lines (58 loc) · 1.43 KB
/
request.go
File metadata and controls
72 lines (58 loc) · 1.43 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
package ulule
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
func (c *Client) apiget(route string, res interface{}) error {
req, err := http.NewRequest("GET", "https://api.ulule.com/v1"+route, nil)
if err != nil {
return err
}
c.authenticate(req)
resp, err := c.httpClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return fmt.Errorf("error %d", resp.StatusCode)
}
decoder := json.NewDecoder(resp.Body)
err = decoder.Decode(res)
if err != nil {
return err
}
return nil
}
func (c *Client) authenticate(req *http.Request) {
if c.username != "" && c.password != "" {
// TODO: basic auth
// curl --basic --user "username:password" https://api.ulule.com/v1/...
} else if c.username != "" && c.apikey != "" {
req.Header.Add("Authorization", "ApiKey "+c.username+":"+c.apikey)
} else if c.accessToken != "" {
req.Header.Add("Authorization", "Bearer "+c.accessToken)
}
}
func (c *Client) apigetJsonBytes(route string) ([]byte, error) {
req, err := http.NewRequest("GET", "https://api.ulule.com/v1"+route, nil)
if err != nil {
return nil, err
}
c.authenticate(req)
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return nil, fmt.Errorf("error %d", resp.StatusCode)
}
jsonBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return jsonBytes, nil
}