gojsonclient

package module
v0.5.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 29, 2024 License: MIT Imports: 10 Imported by: 0

README

GoDoc

gojsonclient

A Go package that provides a client for JSON/REST HTTP services, with automatic retry/backoff.

import "github.com/blizzy78/gojsonclient"

Code example

type request struct {
	Message string `json:"message"`
}

type response struct {
	Reply string `json:"reply"`
}

client := New()

req := NewRequest[*request, *response]("https://www.example.com", http.MethodGet, &request{
	Message: "client",
})

res, _ := Do(context.Background(), client, req)
fmt.Println(res.Res.Reply)

// Output: Hello client!

License

This package is licensed under the MIT license.

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

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

func New(opts ...ClientOpt) *Client

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

func WithBackoff(backoff *gobackoff.Backoff) ClientOpt

WithBackoff configures a Client to use backoff.

func WithBaseURI

func WithBaseURI(baseURI string) ClientOpt

WithBaseURI configures a Client to use baseURI as the URI prefix for all requests.

func WithHTTPClient

func WithHTTPClient(httpClient *http.Client) ClientOpt

WithHTTPClient configures a Client to use httpClient to make requests.

func WithLogger

func WithLogger(logger *slog.Logger) ClientOpt

WithLogger configures a Client to use logger.

func WithMaxAttempts

func WithMaxAttempts(max int) ClientOpt

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

func WithRequestTimeout(timeout time.Duration) ClientOpt

WithRequestTimeout configures a Client to use timeout for each HTTP request made.

func WithRetry

func WithRetry(retry RetryFunc) ClientOpt

WithRetry configures a Client to use retry as the retry function.

type MarshalJSONFunc

type MarshalJSONFunc[T any] func(writer io.Writer, val T) error

MarshalJSONFunc is a function that encodes a value to JSON and outputs it to writer.

type Request

type Request[Req any, Res any] struct {
	// contains filtered or unexported fields
}

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

type RequestMiddlewareFunc func(req *http.Request) error

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

type RequestOpt[Req any, Res any] func(req *Request[Req, Res])

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.

type RetryFunc

type RetryFunc func(ctx context.Context, httpRes *http.Response, err error) error

RetryFunc is a function that decides whether to retry an HTTP request. Depending on the outcome of the previous attempt, httpRes and/or err may be nil. A new attempt is made if the function returns a nil error.

type UnmarshalJSONFunc

type UnmarshalJSONFunc[T any] func(httpRes *http.Response, val *T) error

UnmarshalJSONFunc is a function that decodes JSON from httpRes.Body and stores it in val.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL