This repository has been archived by the owner on Jul 30, 2023. It is now read-only.
/
client.go
78 lines (62 loc) · 1.44 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
package ynab
import (
"context"
"encoding/json"
"net/http"
)
type APIError struct {
ID string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Detail string `json:"detail,omitempty"`
}
func (e APIError) Error() string {
return e.Name
}
type Client struct {
httpClient *http.Client
apiToken string
BaseURL string
}
func NewClient(apiToken string) *Client {
return &Client{
httpClient: &http.Client{},
apiToken: apiToken,
BaseURL: "https://api.youneedabudget.com/v1",
}
}
func (c *Client) Test(ctx context.Context) error {
req, err := c.newRequest(ctx, "GET", "/user")
if err != nil {
return err
}
var payload map[string]interface{}
return c.do(req, &payload)
}
func (c *Client) newRequest(ctx context.Context, method, path string) (*http.Request, error) {
u := c.BaseURL + path
req, err := http.NewRequestWithContext(ctx, method, u, nil)
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/json")
req.Header.Set("Authorization", "Bearer "+c.apiToken)
return req, nil
}
func (c *Client) do(req *http.Request, v interface{}) error {
resp, err := c.httpClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
var payload struct {
Error APIError `json:"error"`
}
if err := json.NewDecoder(resp.Body).Decode(&payload); err != nil {
return err
}
return payload.Error
}
err = json.NewDecoder(resp.Body).Decode(v)
return err
}