diff options
| author | Sam Anthony <sam@samanthony.xyz> | 2026-06-13 11:21:13 -0400 |
|---|---|---|
| committer | Sam Anthony <sam@samanthony.xyz> | 2026-06-13 11:21:13 -0400 |
| commit | 056cff27d3c003e32e098dc59bb53a8a93efa88a (patch) | |
| tree | f67c33f7a251a4d06b9646e5d20f62e8408a1569 /jttp.go | |
| download | jttp-056cff27d3c003e32e098dc59bb53a8a93efa88a.zip | |
Client.Do()
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) +} |