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