blob: 55c3d2dff0524ecd16e30113427b2e3bc119f1da (
plain) (
blame)
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
|
package grocy
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"time"
)
type Client struct {
BaseUrl string
apiKey string
HTTPClient *http.Client
}
func NewClient(baseUrl, apiKey string) *Client {
return &Client{
BaseUrl: baseUrl,
apiKey: apiKey,
HTTPClient: &http.Client{
Timeout: time.Minute,
},
}
}
type ErrorResponse struct {
ErrorMessage string `json:"error_message"`
}
func (c *Client) sendRequest(req *http.Request, v interface{}) error {
req.Header.Set("Content-Type", "application/json; charset=utf-8")
req.Header.Set("Accept", "application/json; charset=utf-8")
req.Header.Set("GROCY-API-KEY", c.apiKey)
res, err := c.HTTPClient.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode < http.StatusOK || res.StatusCode >= http.StatusBadRequest {
var errRes ErrorResponse
if err = json.NewDecoder(res.Body).Decode(&errRes); err == nil {
return errors.New(errRes.ErrorMessage)
}
return fmt.Errorf("unknown error, status code: %d", res.StatusCode)
}
if err = json.NewDecoder(res.Body).Decode(&v); err != nil {
return err
}
return nil
}
|