Compare commits

...

2 Commits

Author SHA1 Message Date
e373e7e273
add error helpers 2020-04-05 18:54:40 -05:00
7fd366823f
remove unused import 2020-04-04 15:30:52 -05:00
2 changed files with 19 additions and 26 deletions

View File

@ -114,6 +114,20 @@ func NewResponse(r *http.Response) (*Response, error) {
return &resp, nil
}
func (r *Response) IsError() bool {
return r.StatusCode > 299
}
func (r *Response) GetLifxError() (err error) {
var (
s *LifxResponse
)
if err = json.NewDecoder(r.Body).Decode(&s); err != nil {
return nil
}
return errors.New(s.Error)
}
func (c *Client) NewRequest(method, url string, body io.Reader) (req *http.Request, err error) {
req, err = http.NewRequest(method, url, body)
if err != nil {

View File

@ -3,8 +3,6 @@ package lifx
import (
//"crypto/tls"
"encoding/json"
"errors"
"fmt"
"net/http"
"time"
)
@ -90,25 +88,6 @@ type (
}
)
func NewApiError(resp *Response) error {
var (
s *LifxResponse
err error
)
if err = json.NewDecoder(resp.Body).Decode(&s); err != nil {
return err
}
return errors.New(s.Error)
}
func IsApiError(resp *Response) bool {
return resp.StatusCode > 299
}
func (s Status) Success() bool {
return s == OK
}
func (c *Client) SetState(selector string, state State) (*LifxResponse, error) {
var (
err error
@ -121,8 +100,8 @@ func (c *Client) SetState(selector string, state State) (*LifxResponse, error) {
}
defer resp.Body.Close()
if IsApiError(resp) {
return nil, NewApiError(resp)
if resp.IsError() {
return nil, resp.GetLifxError()
}
if state.Fast && resp.StatusCode == http.StatusAccepted {
@ -191,8 +170,8 @@ func (c *Client) Toggle(selector string, duration float64) (*LifxResponse, error
}
defer resp.Body.Close()
if IsApiError(resp) {
return nil, NewApiError(resp)
if resp.IsError() {
return nil, resp.GetLifxError()
}
if err = json.NewDecoder(resp.Body).Decode(&s); err != nil {
@ -215,7 +194,7 @@ func (c *Client) ListLights(selector string) ([]Light, error) {
defer resp.Body.Close()
if resp.StatusCode > 299 {
return nil, NewApiError(resp)
return nil, resp.GetLifxError()
}
if err = json.NewDecoder(resp.Body).Decode(&s); err != nil {