feat(httpclient)!: promote to v1.0.0 — retry-on-429 with Retry-After, DoJSONRequest, bump deps
Extend retry loop to handle HTTP 429 Too Many Requests: when the server includes a Retry-After header, that duration is used as the retry delay; otherwise falls back to the configured BackOffDelay. Add DoJSONRequest[Req, Resp] free function that serialises the request body as JSON, sets Content-Type, and delegates response decoding to DoJSON. Bump logz and xerrors from v0.9.0 to v1.0.0. API committed as stable.
This commit is contained in:
16
helpers.go
16
helpers.go
@@ -1,6 +1,7 @@
|
||||
package httpclient
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
@@ -36,6 +37,21 @@ func DoJSON[T any](ctx context.Context, client Client, req *http.Request) (*T, e
|
||||
return &data, nil
|
||||
}
|
||||
|
||||
// DoJSONRequest serialises body as JSON, POST/PUT/PATCHes it to rawURL, and
|
||||
// decodes the response into Resp. For requests without a body, use DoJSON instead.
|
||||
func DoJSONRequest[Req, Resp any](ctx context.Context, client Client, method, rawURL string, body Req) (*Resp, error) {
|
||||
data, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return nil, xerrors.New(xerrors.ErrInternal, "failed to encode request body").WithError(err)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, method, rawURL, bytes.NewReader(data))
|
||||
if err != nil {
|
||||
return nil, xerrors.New(xerrors.ErrInternal, "failed to create request").WithError(err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
return DoJSON[Resp](ctx, client, req)
|
||||
}
|
||||
|
||||
// MapStatusToError maps an HTTP status code to the matching xerrors type.
|
||||
func MapStatusToError(code int, msg string) error {
|
||||
switch code {
|
||||
|
||||
Reference in New Issue
Block a user