more error handling, separate request function

This commit is contained in:
Ryan Cavicchioni 2020-02-25 00:41:29 -06:00
parent 57d7dd6f85
commit 584c2b2ec5
Signed by: ryanc
GPG Key ID: 877EEDAF9245103D
3 changed files with 69 additions and 14 deletions

View File

@ -2,7 +2,7 @@ package main
import (
"fmt"
"git.kill0.net/chill9/lifx"
"git.kill0.net/chill9/go-lifx"
"os"
"time"
)
@ -13,11 +13,14 @@ func main() {
fmt.Println("LIFX_API_TOKEN is undefined")
os.Exit(1)
}
s := &lifx.State{Power: "on", Color: "white"}
s := &lifx.State{Power: "on", Color: "blue"}
c := lifx.NewSession(apiToken)
c.SetState("group:Office", s)
time.Sleep(10 * time.Second)
s.Color = "white"
res, _ := c.SetState("group:Office", s)
fmt.Println(res)
//c.SetState("all", &lifx.State{Power: "on", Color: "green"})
time.Sleep(10)
c.SetState("all", &lifx.State{Power: "on", Color: "green"})
time.Sleep(10)
c.SetState("all", &lifx.State{Power: "off"})
//c.PowerOff("all")
}

60
rest.go
View File

@ -5,6 +5,7 @@ import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
)
@ -15,19 +16,60 @@ func NewSession(token string) *Session {
}
}
func (s *Session) NewRequest(method, url string, body io.Reader) *http.Request {
req, _ := http.NewRequest(method, url, body)
func (s *Session) NewRequest(method, url string, body io.Reader) (req *http.Request, err error) {
req, err = http.NewRequest(method, url, body)
if err != nil {
return
}
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", s.token))
return req
return
}
func (s *Session) SetState(selector string, state *State) error {
j, _ := json.Marshal(state)
req := s.NewRequest("PUT", EndpointState(selector), bytes.NewBuffer(j))
func (s *Session) Request(method, url string, body io.Reader) ([]Result, error) {
req, err := s.NewRequest(method, url, body)
if err != nil {
return []Result{}, err
}
resp, err := s.Client.Do(req)
if err != nil {
return err
return []Result{}, err
}
fmt.Println(resp)
return nil
switch resp.StatusCode {
case http.StatusAccepted:
return []Result{}, nil
case http.StatusMultiStatus:
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return []Result{}, err
}
r := Results{}
err = json.Unmarshal(body, &r)
if err != nil {
return []Result{}, err
}
return r.Results, nil
}
return []Result{}, nil
}
func (s *Session) SetState(selector string, state *State) ([]Result, error) {
j, err := json.Marshal(state)
if err != nil {
return []Result{}, err
}
res, err := s.Request("PUT", EndpointState(selector), bytes.NewBuffer(j))
if err != nil {
return []Result{}, err
}
return res, nil
}
func (s *Session) PowerOff(selector string) {
s.SetState(selector, &State{Power: "off"})
}

View File

@ -21,4 +21,14 @@ type (
token string
Client *http.Client
}
Results struct {
Results []Result `json:results`
}
Result struct {
ID string `json:"id"`
Label string `json:"label"`
Status string `json:"status"`
}
)