refactor SetState function

This commit is contained in:
Ryan Cavicchioni 2020-03-06 01:28:39 -06:00
parent f58f523d35
commit 243d0f6f31
Signed by: ryanc
GPG Key ID: 877EEDAF9245103D

View File

@ -4,6 +4,8 @@ import (
"bytes" "bytes"
//"crypto/tls" //"crypto/tls"
"encoding/json" "encoding/json"
"log"
"net/http"
) )
const ( const (
@ -44,23 +46,33 @@ func (s Status) Success() bool {
} }
func (c *Client) SetState(selector string, state State) ([]Result, error) { func (c *Client) SetState(selector string, state State) ([]Result, error) {
j, err := json.Marshal(state) var (
if err != nil { err error
s *Response
j []byte
req *http.Request
resp *http.Response
)
if j, err = json.Marshal(state); err != nil {
log.Println(err)
return nil, err return nil, err
} }
resp, err := c.Request("PUT", EndpointState(selector), bytes.NewBuffer(j)) if req, err = c.NewRequest("PUT", EndpointState(selector), bytes.NewBuffer(j)); err != nil {
if err != nil { log.Println(err)
return nil, err return nil, err
} }
if state.Fast { if resp, err = c.Client.Do(req); err != nil {
return nil, nil log.Println(err)
return nil, err
} }
s := &Results{} defer resp.Body.Close()
err = c.UnmarshalResponse(resp, s)
if err != nil { if err = json.NewDecoder(resp.Body).Decode(&s); err != nil {
log.Println(err)
return nil, err return nil, err
} }
@ -83,7 +95,7 @@ func (c *Client) SetStates(states States) ([]Result, error) {
return nil, err return nil, err
} }
s := &Results{} s := &Response{}
err = c.UnmarshalResponse(resp, s) err = c.UnmarshalResponse(resp, s)
if err != nil { if err != nil {
return nil, err return nil, err
@ -95,6 +107,7 @@ func (c *Client) SetStates(states States) ([]Result, error) {
func (c *Client) Toggle(selector string, duration float64) ([]Result, error) { func (c *Client) Toggle(selector string, duration float64) ([]Result, error) {
j, err := json.Marshal(&Toggle{Duration: duration}) j, err := json.Marshal(&Toggle{Duration: duration})
if err != nil { if err != nil {
log.Println(err)
return nil, err return nil, err
} }
@ -103,7 +116,7 @@ func (c *Client) Toggle(selector string, duration float64) ([]Result, error) {
return nil, err return nil, err
} }
s := &Results{} s := &Response{}
err = c.UnmarshalResponse(resp, s) err = c.UnmarshalResponse(resp, s)
if err != nil { if err != nil {
return nil, err return nil, err