diff options
Diffstat (limited to 'grocy/grocy.go')
-rw-r--r-- | grocy/grocy.go | 57 |
1 files changed, 57 insertions, 0 deletions
diff --git a/grocy/grocy.go b/grocy/grocy.go new file mode 100644 index 0000000..55c3d2d --- /dev/null +++ b/grocy/grocy.go @@ -0,0 +1,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 +} |