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 | |
| parent | 10f1a7ca7bec98cc65e6c65f7126d1e303b98ef6 (diff) | |
| download | x-da3595468056f1dd04d79c908f8a65dc0c5a397f.tar.xz x-da3595468056f1dd04d79c908f8a65dc0c5a397f.zip | |
web: add NewError function to simplify error creation, use it
| -rw-r--r-- | web/discordwebhook/webhook.go | 20 | ||||
| -rw-r--r-- | web/error.go | 27 |
2 files changed, 27 insertions, 20 deletions
diff --git a/web/discordwebhook/webhook.go b/web/discordwebhook/webhook.go index a5dc1fc..6cbe6d1 100644 --- a/web/discordwebhook/webhook.go +++ b/web/discordwebhook/webhook.go @@ -4,7 +4,6 @@ package discordwebhook import ( "bytes" "encoding/json" - "io/ioutil" "net/http" "github.com/Xe/x/web" @@ -61,24 +60,7 @@ func Send(whurl string, w Webhook) *http.Request { // Validate validates the response from Discord. func Validate(resp *http.Response) error { if resp.StatusCode/100 != 2 { - data, err := ioutil.ReadAll(resp.Body) - if err != nil { - return err - } - resp.Body.Close() - - loc, err := resp.Location() - if err != nil { - return err - } - - return &web.Error{ - WantStatus: 200, - GotStatus: resp.StatusCode, - URL: loc, - Method: resp.Request.Method, - ResponseBody: string(data), - } + return web.NewError(http.StatusOK, resp) } return nil 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 |
