From 61af6c5cfd773db569910f2473499db67a5a8810 Mon Sep 17 00:00:00 2001 From: Collin Guarino Date: Tue, 2 Feb 2016 23:47:24 -0500 Subject: Added handleResponse and bridge.Error to manage http responses and bridge specific errors with rest calls. --- bridge.go | 40 +++++++++++++++++++++++++++++----------- 1 file changed, 29 insertions(+), 11 deletions(-) diff --git a/bridge.go b/bridge.go index 942318a..54000e3 100644 --- a/bridge.go +++ b/bridge.go @@ -42,26 +42,44 @@ type Device struct { func (self *Bridge) Get(path string) ([]byte, io.Reader, error) { resp, err := http.Get("http://" + self.IPAddress + path) - if err != nil { - trace("", err) - } else if resp.StatusCode != 200 { - trace(fmt.Sprintf("Bridge status error: %d", resp.StatusCode), nil) + if self.Error(resp, err) { + return []byte{}, nil, err } - //defer resp.Body.Close() + return handleResponse(resp) +} + +func (self *Bridge) Post(path string) ([]byte, io.Reader, error) { + // resp, err := http.Post("http://" + self.IpAddress + path) + // if err != nil { + // trace("", err) + // } + return []byte{}, nil, nil +} + +// HandleResponse manages the http.Response from a bridge Get/Put/Post/Delete +// by checking it for errors and invalid return types. +func handleResponse(resp *http.Response) ([]byte, io.Reader, error) { body, err := ioutil.ReadAll(resp.Body) if err != nil { trace("Error parsing bridge description xml.", nil) + return []byte{}, nil, err } reader := bytes.NewReader(body) - // TODO: handle individual error codes + return body, reader, nil } -func (self *Bridge) Post(path string) ([]byte, io.Reader, error) { - // resp, err := http.Post("http://" + self.IpAddress + path) - // if err != nil { - // trace("", err) - // } +// bridge.Error handles any bridge request or response errors +func (self *Bridge) Error(resp *http.Response, err error) (bool) { + if err != nil { + trace("", err) + return true + } else if resp.StatusCode != 200 { + // TODO: handle other status codes + trace(fmt.Sprintf("Bridge status error: %d", resp.StatusCode), nil) + return true + } + return false } // Error Struct -- cgit v1.2.3