-
Notifications
You must be signed in to change notification settings - Fork 5
/
api.go
59 lines (53 loc) · 1.22 KB
/
api.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 forecast
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/http/cookiejar"
)
// API provides access to the forecastapp.com API
type API struct {
URL string
AccountID string
token string `ignored:"true"`
client *http.Client `ignored:"true"`
}
// New returns a API that is authenticated with Forecast
func New(url string, accountID string, accessToken string) *API {
return &API{
URL: url,
AccountID: accountID,
token: accessToken,
}
}
func (api *API) do(path string, result interface{}) error {
req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/%s", api.URL, path), nil)
if err != nil {
return err
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", api.token))
req.Header.Set("Forecast-Account-ID", api.AccountID)
if api.client == nil {
jar, e := cookiejar.New(nil)
if e != nil {
return e
}
api.client = &http.Client{
Jar: jar,
}
}
r, err := api.client.Do(req)
if err != nil {
return err
}
defer r.Body.Close()
if r.StatusCode >= http.StatusBadRequest {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return err
}
return fmt.Errorf("%s: %s", r.Status, string(body))
}
return json.NewDecoder(r.Body).Decode(result)
}