blob: 55c3d2dff0524ecd16e30113427b2e3bc119f1da (
plain) (
tree)
|
|
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
}
|