diff options
| author | Christine Dodrill <me@christine.website> | 2019-01-29 03:35:41 -0800 |
|---|---|---|
| committer | Christine Dodrill <me@christine.website> | 2019-01-29 03:35:41 -0800 |
| commit | da3595468056f1dd04d79c908f8a65dc0c5a397f (patch) | |
| tree | 35b21eed538f3e2f9cc1282c71ebcbda420f7c9d /web/error.go | |
| parent | 10f1a7ca7bec98cc65e6c65f7126d1e303b98ef6 (diff) | |
| download | x-da3595468056f1dd04d79c908f8a65dc0c5a397f.tar.xz x-da3595468056f1dd04d79c908f8a65dc0c5a397f.zip | |
web: add NewError function to simplify error creation, use it
Diffstat (limited to 'web/error.go')
| -rw-r--r-- | web/error.go | 27 |
1 files changed, 26 insertions, 1 deletions
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 |
