From da3595468056f1dd04d79c908f8a65dc0c5a397f Mon Sep 17 00:00:00 2001 From: Christine Dodrill Date: Tue, 29 Jan 2019 03:35:41 -0800 Subject: web: add NewError function to simplify error creation, use it --- web/error.go | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) (limited to 'web/error.go') diff --git a/web/error.go b/web/error.go index e4ffcab..051d61d 100644 --- a/web/error.go +++ b/web/error.go @@ -4,12 +4,37 @@ package web import ( "fmt" + "io/ioutil" + "net/http" "net/url" "within.website/ln" ) -// Error is an API error. +// NewError creates an Error based on an expected HTTP status code vs data populated +// from an HTTP response. +func NewError(wantStatusCode int, resp *http.Response) error { + data, err := ioutil.ReadAll(resp.Body) + if err != nil { + return err + } + resp.Body.Close() + + loc, err := resp.Location() + if err != nil { + return err + } + + return &Error{ + WantStatus: wantStatusCode, + GotStatus: resp.StatusCode, + URL: loc, + Method: resp.Request.Method, + ResponseBody: string(data), + } +} + +// Error is a web response error. Use this when API calls don't work out like you wanted them to. type Error struct { WantStatus, GotStatus int URL *url.URL -- cgit v1.2.3