| 1 |
// Package jsonclient provides a JSON HTTP client for making HTTP requests |
| 2 |
// that automatically marshal and unmarshal JSON payloads. |
| 3 |
package jsonclient |
| 4 |
|
| 5 |
import ( |
| 6 |
"bytes" |
| 7 |
"context" |
| 8 |
"encoding/json" |
| 9 |
"errors" |
| 10 |
"fmt" |
| 11 |
"io" |
| 12 |
"net/http" |
| 13 |
) |
| 14 |
|
| 15 |
// Client defines the interface for JSON HTTP operations. |
| 16 |
type Client interface { |
| 17 |
Get(url string, response any) error |
| 18 |
Post(url string, request, response any) error |
| 19 |
Headers() http.Header |
| 20 |
ErrorResponse(err error, response any) bool |
| 21 |
} |
| 22 |
|
| 23 |
// Error contains additional HTTP/JSON details. |
| 24 |
type Error struct { |
| 25 |
StatusCode int |
| 26 |
Body string |
| 27 |
err error |
| 28 |
} |
| 29 |
|
| 30 |
// client wraps http.Client for JSON operations. |
| 31 |
type client struct { |
| 32 |
httpClient *http.Client |
| 33 |
headers http.Header |
| 34 |
indent string |
| 35 |
} |
| 36 |
|
| 37 |
// ContentType defines the default MIME type for JSON requests. |
| 38 |
const ContentType = "application/json" |
| 39 |
|
| 40 |
// HTTPClientErrorThreshold specifies the status code threshold for client errors (400+). |
| 41 |
const HTTPClientErrorThreshold = 400 |
| 42 |
|
| 43 |
// ErrUnexpectedStatus indicates an unexpected HTTP response status. |
| 44 |
var ErrUnexpectedStatus = errors.New("got unexpected HTTP status") |
| 45 |
|
| 46 |
// DefaultClient provides a singleton JSON client using http.DefaultClient. |
| 47 |
var DefaultClient = NewClient() |
| 48 |
|
| 49 |
// Error returns the string representation of the error. |
| 50 |
func (je Error) Error() string { |
| 51 |
return je.String() |
| 52 |
} |
| 53 |
|
| 54 |
// String provides a human-readable description of the error. |
| 55 |
func (je Error) String() string { |
| 56 |
if je.err == nil { |
| 57 |
return fmt.Sprintf("unknown error (HTTP %v)", je.StatusCode) |
| 58 |
} |
| 59 |
|
| 60 |
return je.err.Error() |
| 61 |
} |
| 62 |
|
| 63 |
// ErrorBody extracts the request body from an error if it's a jsonclient.Error. |
| 64 |
func ErrorBody(e error) string { |
| 65 |
var jsonError Error |
| 66 |
if errors.As(e, &jsonError) { |
| 67 |
return jsonError.Body |
| 68 |
} |
| 69 |
|
| 70 |
return "" |
| 71 |
} |
| 72 |
|
| 73 |
// NewClient creates a new JSON client using the default http.Client. |
| 74 |
func NewClient() Client { |
| 75 |
return NewWithHTTPClient(http.DefaultClient) |
| 76 |
} |
| 77 |
|
| 78 |
// NewWithHTTPClient creates a new JSON client using the specified http.Client. |
| 79 |
func NewWithHTTPClient(httpClient *http.Client) Client { |
| 80 |
return &client{ |
| 81 |
httpClient: httpClient, |
| 82 |
headers: http.Header{ |
| 83 |
"Content-Type": []string{ContentType}, |
| 84 |
}, |
| 85 |
indent: "", |
| 86 |
} |
| 87 |
} |
| 88 |
|
| 89 |
// Get fetches a URL using GET and unmarshals the response into the provided object using DefaultClient. |
| 90 |
func Get(url string, response any) error { |
| 91 |
if err := DefaultClient.Get(url, response); err != nil { |
| 92 |
return fmt.Errorf("getting JSON from %q: %w", url, err) |
| 93 |
} |
| 94 |
|
| 95 |
return nil |
| 96 |
} |
| 97 |
|
| 98 |
// Post sends a request as JSON and unmarshals the response into the provided object using DefaultClient. |
| 99 |
func Post(url string, request, response any) error { |
| 100 |
if err := DefaultClient.Post(url, request, response); err != nil { |
| 101 |
return fmt.Errorf("posting JSON to %q: %w", url, err) |
| 102 |
} |
| 103 |
|
| 104 |
return nil |
| 105 |
} |
| 106 |
|
| 107 |
// ErrorResponse checks if an error is a JSON error and unmarshals its body into the response. |
| 108 |
func (c *client) ErrorResponse(err error, response any) bool { |
| 109 |
var errMsg Error |
| 110 |
if errors.As(err, &errMsg) { |
| 111 |
return json.Unmarshal([]byte(errMsg.Body), response) == nil |
| 112 |
} |
| 113 |
|
| 114 |
return false |
| 115 |
} |
| 116 |
|
| 117 |
// Get fetches a URL using GET and unmarshals the response into the provided object. |
| 118 |
func (c *client) Get(url string, response any) error { |
| 119 |
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, url, http.NoBody) |
| 120 |
if err != nil { |
| 121 |
return fmt.Errorf("creating GET request for %q: %w", url, err) |
| 122 |
} |
| 123 |
|
| 124 |
for key, val := range c.headers { |
| 125 |
req.Header.Set(key, val[0]) |
| 126 |
} |
| 127 |
|
| 128 |
res, err := c.httpClient.Do(req) |
| 129 |
if err != nil { |
| 130 |
return fmt.Errorf("executing GET request to %q: %w", url, err) |
| 131 |
} |
| 132 |
|
| 133 |
defer func() { _ = res.Body.Close() }() |
| 134 |
|
| 135 |
return parseResponse(res, response) |
| 136 |
} |
| 137 |
|
| 138 |
// Headers returns the default headers for requests. |
| 139 |
func (c *client) Headers() http.Header { |
| 140 |
return c.headers |
| 141 |
} |
| 142 |
|
| 143 |
// Post sends a request as JSON and unmarshals the response into the provided object. |
| 144 |
func (c *client) Post(url string, request, response any) error { |
| 145 |
var err error |
| 146 |
|
| 147 |
var body []byte |
| 148 |
|
| 149 |
if strReq, ok := request.(string); ok { |
| 150 |
// If the request is a string, pass it through without serializing |
| 151 |
body = []byte(strReq) |
| 152 |
} else { |
| 153 |
body, err = json.MarshalIndent(request, "", c.indent) |
| 154 |
if err != nil { |
| 155 |
return fmt.Errorf("marshaling request to JSON: %w", err) |
| 156 |
} |
| 157 |
} |
| 158 |
|
| 159 |
req, err := http.NewRequestWithContext( |
| 160 |
context.Background(), |
| 161 |
http.MethodPost, |
| 162 |
url, |
| 163 |
bytes.NewReader(body), |
| 164 |
) |
| 165 |
if err != nil { |
| 166 |
return fmt.Errorf("creating POST request for %q: %w", url, err) |
| 167 |
} |
| 168 |
|
| 169 |
for key, val := range c.headers { |
| 170 |
req.Header.Set(key, val[0]) |
| 171 |
} |
| 172 |
|
| 173 |
res, err := c.httpClient.Do(req) |
| 174 |
if err != nil { |
| 175 |
return fmt.Errorf("sending POST request to %q: %w", url, err) |
| 176 |
} |
| 177 |
|
| 178 |
defer func() { _ = res.Body.Close() }() |
| 179 |
|
| 180 |
return parseResponse(res, response) |
| 181 |
} |
| 182 |
|
| 183 |
// parseResponse parses the HTTP response and unmarshals it into the provided object. |
| 184 |
func parseResponse(res *http.Response, response any) error { |
| 185 |
body, err := io.ReadAll(res.Body) |
| 186 |
|
| 187 |
if res.StatusCode >= HTTPClientErrorThreshold { |
| 188 |
err = fmt.Errorf("%w: %v", ErrUnexpectedStatus, res.Status) |
| 189 |
} |
| 190 |
|
| 191 |
if err == nil { |
| 192 |
err = json.Unmarshal(body, response) |
| 193 |
} |
| 194 |
|
| 195 |
if err != nil { |
| 196 |
if body == nil { |
| 197 |
body = []byte{} |
| 198 |
} |
| 199 |
|
| 200 |
return Error{ |
| 201 |
StatusCode: res.StatusCode, |
| 202 |
Body: string(body), |
| 203 |
err: err, |
| 204 |
} |
| 205 |
} |
| 206 |
|
| 207 |
return nil |
| 208 |
} |