diff options
Diffstat (limited to 'jttp.go')
| -rw-r--r-- | jttp.go | 34 |
1 files changed, 34 insertions, 0 deletions
@@ -0,0 +1,34 @@ +package jttp + +import ( + "encoding/json" + "fmt" + "net/http" +) + +type Client struct { + c *http.Client +} + +func NewClient(c *http.Client) *Client { + return &Client{c} +} + +// Do sends an HTTP request, checks that the response status code matches +// wantStatus, and decodes the JSON response body into resp. +// +// An error is returned if the HTTP request fails, the response status +// code does not equal wantStatus, or the JSON decoding fails. +func (c *Client) Do(req *http.Request, wantStatus int, resp any) error { + hresp, err := c.c.Do(req) + if err != nil { + return err + } + defer hresp.Body.Close() + if hresp.StatusCode != wantStatus { + return fmt.Errorf("jttp: %s %s: %s (expected %d)", + req.Method, req.URL, hresp.Status, wantStatus) + } + dec := json.NewDecoder(hresp.Body) + return dec.Decode(resp) +} |