forked from mattatcha/harvest
-
Notifications
You must be signed in to change notification settings - Fork 1
/
harvest.go
78 lines (62 loc) · 1.41 KB
/
harvest.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 harvest
import (
"encoding/base64"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
)
func NewCient(domain, username, password string) (*Client, error) {
base := fmt.Sprint("https://", domain, ".harvestapp.com")
baseURL, err := url.Parse(base)
if err != nil {
return nil, err
}
userPass := fmt.Sprint(username, ":", password)
encoded := base64.StdEncoding.EncodeToString([]byte(userPass))
return &Client{
encodedAuth: encoded,
baseURL: baseURL,
client: &http.Client{},
}, nil
}
func (c *Client) NewRequest(method, path string, body io.Reader) (*http.Request, error) {
url := *c.baseURL
url.Path = path
req, err := http.NewRequest(method, url.String(), body)
if err != nil {
return nil, err
}
req.Header = http.Header{
"Accept": {"application/json"},
"Content-Type": {"application/json"},
"Authorization": {"Basic " + c.encodedAuth},
}
return req, nil
}
func (c *Client) do(request *http.Request) (*http.Response, error) {
return c.client.Do(request)
}
func (c *Client) Daily() (*Daily, error) {
req, err := c.NewRequest("GET", "/daily", nil)
if err != nil {
return nil, err
}
res, err := c.do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
daily := &Daily{}
err = json.Unmarshal(body, daily)
if err != nil {
return nil, err
}
return daily, nil
}