Documentation ¶
Overview ¶
Package gojsonclient provides a client for JSON/REST HTTP services.
Example ¶
type request struct { Message string `json:"message"` } type response struct { Reply string `json:"reply"` } server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, httpReq *http.Request) { var req *request _ = json.UnmarshalRead(httpReq.Body, &req) _ = json.MarshalWrite(writer, &response{ Reply: "Hello " + req.Message + "!", }) })) defer server.Close() client := New() req := NewRequest[*request, *response](server.URL+"/foo", http.MethodGet, &request{ Message: "client", }) res, _ := Do(context.Background(), client, req) fmt.Println(res.Res.Reply)
Output: Hello client!
Index ¶
- type Client
- type ClientOpt
- func WithBackoff(backoff *gobackoff.Backoff) ClientOpt
- func WithBaseURI(baseURI string) ClientOpt
- func WithHTTPClient(httpClient *http.Client) ClientOpt
- func WithLogger(logger *slog.Logger) ClientOpt
- func WithMaxAttempts(max int) ClientOpt
- func WithRequestMiddleware(fun RequestMiddlewareFunc) ClientOpt
- func WithRequestTimeout(timeout time.Duration) ClientOpt
- func WithRetry(retry RetryFunc) ClientOpt
- type MarshalJSONFunc
- type Request
- type RequestMiddlewareFunc
- type RequestOpt
- type Response
- type RetryFunc
- type UnmarshalJSONFunc
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is a client for JSON/REST HTTP services.
func New ¶
New creates a new Client with the given options.
The default options are: slog.Default() as the logger, http.DefaultClient as the HTTP client, request timeout of 30s, maximum number of attempts of 5, gobackoff.New() as the backoff, and a retry function that returns an error if the HTTP response status code is http.StatusBadRequest.
func (*Client) Use ¶ added in v0.3.0
func (c *Client) Use(fun RequestMiddlewareFunc)
Use configures c to use fun as a request middleware. Any number of request middlewares may be added.
A Client should usually be configured using WithRequestMiddleware, but it may sometimes be necessary to add new middlewares after the Client has been created.
type ClientOpt ¶
type ClientOpt func(client *Client)
ClientOpt is a function that configures a Client.
func WithBackoff ¶
WithBackoff configures a Client to use backoff.
func WithBaseURI ¶
WithBaseURI configures a Client to use baseURI as the URI prefix for all requests.
func WithHTTPClient ¶
WithHTTPClient configures a Client to use httpClient to make requests.
func WithLogger ¶
WithLogger configures a Client to use logger.
func WithMaxAttempts ¶
WithMaxAttempts configures a Client to make at most max attempts for each request.
func WithRequestMiddleware ¶
func WithRequestMiddleware(fun RequestMiddlewareFunc) ClientOpt
WithRequestMiddleware configures a Client to use fun as a request middleware. Any number of request middlewares may be added.
func WithRequestTimeout ¶
WithRequestTimeout configures a Client to use timeout for each HTTP request made.
type MarshalJSONFunc ¶
MarshalJSONFunc is a function that encodes a value to JSON and outputs it to writer.
type Request ¶
Request represents a JSON/REST HTTP request.
func NewRequest ¶
func NewRequest[Req any, Res any](uri string, method string, req Req, opts ...RequestOpt[Req, Res]) *Request[Req, Res]
NewRequest creates a new Request with the given client, URI, method, request data, and options.
type RequestMiddlewareFunc ¶
RequestMiddlewareFunc is a function that modifies an HTTP request.
func BasicAuth ¶
func BasicAuth(login string, password string) RequestMiddlewareFunc
BasicAuth returns a request middleware that sets the request's Authorization header to use HTTP Basic authentication with the provided username and password.
func BearerAuth ¶
func BearerAuth(token string) RequestMiddlewareFunc
BearerAuth returns a request middleware that sets the request's Authorization header to use HTTP Bearer authentication with the provided token. The token will be inserted verbatim and may need to be encoded first.
type RequestOpt ¶
RequestOpt is a function that configures a Request.
func WithIgnoreResponseBody ¶ added in v0.5.0
func WithIgnoreResponseBody[Req any, Res any]() RequestOpt[Req, Res]
WithIgnoreResponseBody configures a Request to ignore the response body, regardless of status code. The response body will always be ignored if the status code is http.StatusNoContent.
func WithMarshalRequestFunc ¶
func WithMarshalRequestFunc[Req any, Res any](fun MarshalJSONFunc[Req]) RequestOpt[Req, Res]
WithMarshalRequestFunc configures a Request to use fun as the marshal function.
func WithUnmarshalResponseFunc ¶
func WithUnmarshalResponseFunc[Req any, Res any](fun UnmarshalJSONFunc[Res]) RequestOpt[Req, Res]
WithUnmarshalResponseFunc configures a Request to use fun as the unmarshal function.
type Response ¶
type Response[T any] struct { // Res is the value decoded from the response body. // Res will be the default value of T if StatusCode==http.StatusNoContent, or if the response body is ignored. Res T // StatusCode is the HTTP response status code. StatusCode int // Status is the HTTP response status. Status string }
Response represents a JSON/REST HTTP response.
func Do ¶
func Do[Req any, Res any](ctx context.Context, client *Client, req *Request[Req, Res]) (*Response[Res], error)
Do executes req with client and returns the response.
If the request data is nil, the request will be made without a body. If the response status code is http.StatusNoContent or the response body should be ignored, Response.Res will be the default value of Res.
If an HTTP request fails, it is retried using backoff according to the retry function, up to the maximum number of attempts. If the context is canceled, or if the retry function returns a non-nil error, Do stops and returns a gobackoff.AbortError.
Do is safe to call concurrently with the same Request.