blob: 34c6fd607f56ccccfdc380de40fecadaefeab322 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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)
}
|