aboutsummaryrefslogtreecommitdiffstats
path: root/jttp.go
diff options
context:
space:
mode:
authorSam Anthony <sam@samanthony.xyz>2026-06-13 11:21:13 -0400
committerSam Anthony <sam@samanthony.xyz>2026-06-13 11:21:13 -0400
commit056cff27d3c003e32e098dc59bb53a8a93efa88a (patch)
treef67c33f7a251a4d06b9646e5d20f62e8408a1569 /jttp.go
downloadjttp-056cff27d3c003e32e098dc59bb53a8a93efa88a.zip
Client.Do()
Diffstat (limited to 'jttp.go')
-rw-r--r--jttp.go34
1 files changed, 34 insertions, 0 deletions
diff --git a/jttp.go b/jttp.go
new file mode 100644
index 0000000..34c6fd6
--- /dev/null
+++ b/jttp.go
@@ -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)
+}