forked from cozy/cozy-stack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
107 lines (97 loc) · 2.27 KB
/
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package manager
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"net/http"
"time"
"golang.org/x/oauth2"
)
// tokenSource implements the oauth2.TokenSource interface
type tokenSource struct {
token string
}
func (t *tokenSource) Token() (*oauth2.Token, error) {
token := &oauth2.Token{
AccessToken: t.token,
}
return token, nil
}
// APIClient is an http client that can be used to query the API of the
// manager.
type APIClient struct {
baseURL string
client *http.Client
}
// NewAPIClient builds a new client for the manager API
func NewAPIClient(baseURL, token string) *APIClient {
tokenSource := &tokenSource{token: token}
client := oauth2.NewClient(context.Background(), tokenSource)
client.Timeout = 15 * time.Second
return &APIClient{
baseURL: baseURL,
client: client,
}
}
// Do makes a request to the manager API
func (c *APIClient) Do(method, url string, body io.Reader) (*http.Response, error) {
req, err := http.NewRequest(method, c.baseURL+url, body)
if err != nil {
return nil, err
}
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
return c.client.Do(req)
}
// Get makes a GET request to the manager API
func (c *APIClient) Get(url string) (map[string]interface{}, error) {
res, err := c.Do(http.MethodGet, url, nil)
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode >= 400 {
return nil, errors.New(res.Status)
}
var data map[string]interface{}
if err := json.NewDecoder(res.Body).Decode(&data); err != nil {
return nil, err
}
return data, nil
}
// Put makes a PUT request to the manager API
func (c *APIClient) Put(url string, params map[string]interface{}) error {
body, err := json.Marshal(params)
if err != nil {
return err
}
reader := bytes.NewReader(body)
res, err := c.Do(http.MethodPut, url, reader)
if err != nil {
return err
}
if err := res.Body.Close(); err != nil {
return err
}
if res.StatusCode >= 400 {
return errors.New(res.Status)
}
return nil
}
// Delete makes a DELETE request to the manager API
func (c *APIClient) Delete(url string) error {
res, err := c.Do(http.MethodDelete, url, nil)
if err != nil {
return err
}
if err := res.Body.Close(); err != nil {
return err
}
if res.StatusCode >= 400 {
return errors.New(res.Status)
}
return nil
}