| 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 | var jsonError Error |
| 71 | if errors.As(e, &jsonError) { |
| 72 | return jsonError.Body |
| 73 | } |
| 74 | |
| 75 | return "" |
| 76 | } |
| 77 | |
| 78 | // NewClient creates a new JSON client using the default http.Client. |
| 79 | // |
| 80 | // Deprecated: Use NewWithHTTPClient with an explicit client instead. |
| 81 | func NewClient() Client { |
| 82 | return NewWithHTTPClient(http.DefaultClient) |
| 83 | } |
| 84 | |
| 85 | // NewWithHTTPClient creates a new JSON client using the specified HTTP client. |
| 86 | func NewWithHTTPClient(httpClient types.HTTPClient) Client { |
| 87 | return &client{ |
| 88 | httpClient: httpClient, |
| 89 | headers: http.Header{ |
| 90 | "Content-Type": []string{ContentType}, |
| 91 | }, |
| 92 | indent: "", |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | // Get fetches a URL using GET and unmarshals the response into the provided object using DefaultClient. |
| 97 | // |
| 98 | // Deprecated: Create a Client with NewWithHTTPClient and call Get on it instead. |
| 99 | func Get(url string, response any) error { |
| 100 | if err := DefaultClient.Get(url, response); err != nil { |
| 101 | return fmt.Errorf("getting JSON from %q: %w", url, err) |
| 102 | } |
| 103 | |
| 104 | return nil |
| 105 | } |
| 106 | |
| 107 | // Post sends a request as JSON and unmarshals the response into the provided object using DefaultClient. |
| 108 | // |
| 109 | // Deprecated: Create a Client with NewWithHTTPClient and call Post on it instead. |
| 110 | func Post(url string, request, response any) error { |
| 111 | if err := DefaultClient.Post(url, request, response); err != nil { |
| 112 | return fmt.Errorf("posting JSON to %q: %w", url, err) |
| 113 | } |
| 114 | |
| 115 | return nil |
| 116 | } |
| 117 | |
| 118 | // ErrorResponse checks if an error is a JSON error and unmarshals its body into the response. |
| 119 | func (c *client) ErrorResponse(err error, response any) bool { |
| 120 | var errMsg Error |
| 121 | if errors.As(err, &errMsg) { |
| 122 | return json.Unmarshal([]byte(errMsg.Body), response) == nil |
| 123 | } |
| 124 | |
| 125 | return false |
| 126 | } |
| 127 | |
| 128 | // Get fetches a URL using GET and unmarshals the response into the provided object. |
| 129 | func (c *client) Get(url string, response any) error { |
| 130 | req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, url, http.NoBody) |
| 131 | if err != nil { |
| 132 | return fmt.Errorf("creating GET request for %q: %w", url, err) |
| 133 | } |
| 134 | |
| 135 | for key, val := range c.headers { |
| 136 | req.Header.Set(key, val[0]) |
| 137 | } |
| 138 | |
| 139 | res, err := c.httpClient.Do(req) |
| 140 | if err != nil { |
| 141 | return fmt.Errorf("executing GET request to %q: %w", url, err) |
| 142 | } |
| 143 | |
| 144 | defer func() { _ = res.Body.Close() }() |
| 145 | |
| 146 | return parseResponse(res, response) |
| 147 | } |
| 148 | |
| 149 | // Headers returns the default headers for requests. |
| 150 | func (c *client) Headers() http.Header { |
| 151 | return c.headers |
| 152 | } |
| 153 | |
| 154 | // Post sends a request as JSON and unmarshals the response into the provided object. |
| 155 | func (c *client) Post(url string, request, response any) error { |
| 156 | var err error |
| 157 | |
| 158 | var body []byte |
| 159 | |
| 160 | if strReq, ok := request.(string); ok { |
| 161 | // If the request is a string, pass it through without serializing |
| 162 | body = []byte(strReq) |
| 163 | } else { |
| 164 | body, err = json.MarshalIndent(request, "", c.indent) |
| 165 | if err != nil { |
| 166 | return fmt.Errorf("marshaling request to JSON: %w", err) |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | req, err := http.NewRequestWithContext( |
| 171 | context.Background(), |
| 172 | http.MethodPost, |
| 173 | url, |
| 174 | bytes.NewReader(body), |
| 175 | ) |
| 176 | if err != nil { |
| 177 | return fmt.Errorf("creating POST request for %q: %w", url, err) |
| 178 | } |
| 179 | |
| 180 | for key, val := range c.headers { |
| 181 | req.Header.Set(key, val[0]) |
| 182 | } |
| 183 | |
| 184 | res, err := c.httpClient.Do(req) |
| 185 | if err != nil { |
| 186 | return fmt.Errorf("sending POST request to %q: %w", url, err) |
| 187 | } |
| 188 | |
| 189 | defer func() { _ = res.Body.Close() }() |
| 190 | |
| 191 | return parseResponse(res, response) |
| 192 | } |
| 193 | |
| 194 | // parseResponse parses the HTTP response and unmarshals it into the provided object. |
| 195 | func parseResponse(res *http.Response, response any) error { |
| 196 | body, err := io.ReadAll(res.Body) |
| 197 | |
| 198 | if res.StatusCode >= HTTPClientErrorThreshold { |
| 199 | err = fmt.Errorf("%w: %v", ErrUnexpectedStatus, res.Status) |
| 200 | } |
| 201 | |
| 202 | if err == nil { |
| 203 | err = json.Unmarshal(body, response) |
| 204 | } |
| 205 | |
| 206 | if err != nil { |
| 207 | if body == nil { |
| 208 | body = []byte{} |
| 209 | } |
| 210 | |
| 211 | return Error{ |
| 212 | StatusCode: res.StatusCode, |
| 213 | Body: string(body), |
| 214 | err: err, |
| 215 | } |
| 216 | } |
| 217 | |
| 218 | return nil |
| 219 | } |