gent

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: May 26, 2024 License: MIT Imports: 8 Imported by: 1

README

Go HTTP Client

Build Coverage Go Report Card Go Reference

Gent is a Golang HTTP Client wrapper that provides additional features for flexibility and increased performance.

Usage

Create a Client that lets you to make requests. The constructor accepts a list of options to customize it.

// Default client
cl := gent.NewClient()

To make requests, use the functions named after HTTP methods. The following example sends a POST request to http://localhost:8080/employees/create with an application/json body containing an employee id and name, an Authorization header, and a query parameter set to true.

res, err := cl.Post(
    context.Background(),
    "http://localhost:8080/{}/{}",
    map[string]string{
        "id": "4481e035-1711-419f-82bc-bfb72da06375",
        "name": "John Smith",
    },
    gent.NewJSONMarshaler(),
    map[string]string{
 		"Authorization": "Bearer x.y.z",
	},
    map[string][]string{
 		"strict":    {"true"},
 	},
    "employees",
    "create",
)
Request Builder ⭒NEW⭒

Requests can be constructed gradually with a request builder. Request require at least an HTTP method and an endpoint, the other parameters are optional.

res, err := cl.NewRequest(
    http.MethodGet, "http://localhost:8080/{}/{}",
).WithBody(
    map[string]string{
        "id": "4481e035-1711-419f-82bc-bfb72da06375",
        "name": "John Smith",
    },
    gent.NewJSONMarshaler(),
).WithHeaders(
    map[string]string{"Authorization": "Bearer x.y.z"},
).WithQueryParameters(
    map[string][]string{"strict": {"true"},},
).WithPathParameters(
    "employees", "create",
).Run(context.Background())
Placeholders

The request's endpoint supports placeholders in the form of {}. Placeholders will be populated by the trailing variadic path parameters that get escaped before replacing the placeholders in the order they were provided.

Request Body

Any data can be provided as a request body, and it is up to the marshaler to transform it into a byte array for the request. By default the package supports JSON, XML and Form marshalers. If you do not require a request body, leave both the body and the marshaler nil.

Marshalers must implement Marshal(body any) (data []byte, content string, err error), which take any input and return a byte array data, a content type for the header and any error. The following is the implementation of the JSON Marshaler for reference.

type jsonMarshaler struct{}

func (m *jsonMarshaler) Marshal(
    v any,
) (dat []byte, t string, err error) {
	t = "application/json"
	dat, err = json.Marshal(v)
	return
}
Query Parameters

Query parameters are constructed from a map and include a ? if there is at least one query parameter provided. It is recommended to add query parameters via the map, as they get escaped. Parameters support arrays, which get added in the following format:

map[string][]string{
    // ?ids=123&ids=456&ids=789
    "ids": {"123", "456", "789"}
}

Options and Modules

The Client can be configured during creation with a variety of options.

cl := gent.NewClient(
    /* ... Option */
)
HTTP Client

The client internally uses the default HTTP Client to make requests. This can be changed with the UseHttpClient option. The default behavior is to reuse clients between requests. This can also be changed by providing a constructor function that returns a new client for each request.

// Client that uses a new HTTP client
cl := gent.NewClient(
    gent.UseHttpClient(&http.Client{}),
)
// Client that creates a new HTTP client for each request
cl := gent.NewClient(
    gent.UseHttpClientConstructor(func() gent.HttpClient{
        return &http.Client{}
    }),
)
Memory Pool

Each client uses a memory pool internally to speed up string operations by reusing memory allocations. By default, each client creates its own memory pool with default page sizes and pool sizes. A pre-configured memory pool can be provided to and even shared between clients.

cl := gent.NewClient(
    gent.UseMemoryPool(gent.NewMemPool(
        512, // Page size in bytes
        200, // Pool size in pages
    )),
)

You can provide your own implementation of memory pool if it implements how to acquire byte arrays from the pool with Acquire() []byte and release byte arrays into the pool with Release(...[]byte)

Middlewares

Clients can be given middlewares that are executed for each request. Middlewares can be added to two stages. BeforeBuild middlewares run before the http.Request object is created, while BeforeExecute middlewares run before the request is sent.

To add a middleware, use the Use function on the client.

cl := gent.NewClient()

// Middleware that adds an auth header to the request
cl.Use(
    gent.MDW_BeforeBuild, 
    func(c context.Context, r *gent.Request) {
        r.Headers["Authorization"] = "Bearer x.y.z"
        r.Next()
    },
)

Documentation

Index

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 wraps an http.Client with additional functionality.

func NewClient

func NewClient(opts ...Option) *Client

NewClient creates a Client with options.

func (*Client) Delete

func (c *Client) Delete(
	ctx context.Context,
	endpoint string,
	body any,
	marshaler Marshaler,
	headers map[string]string,
	queryParam map[string][]string,
	pathParams ...string,
) (res *http.Response, err error)

Delete runs an http DELETE request with all the given parameters.

func (*Client) Do

func (c *Client) Do(
	ctx context.Context,
	method string,
	endpoint string,
	body any,
	marshaler Marshaler,
	headers map[string]string,
	queryParam map[string][]string,
	pathParams ...string,
) (res *http.Response, err error)

Do runs an http request with all the given parameters.

func (*Client) Get

func (c *Client) Get(
	ctx context.Context,
	endpoint string,
	body any,
	marshaler Marshaler,
	headers map[string]string,
	queryParam map[string][]string,
	pathParams ...string,
) (res *http.Response, err error)

Get runs an http GET request with all the given parameters.

func (*Client) NewRequest added in v0.2.0

func (c *Client) NewRequest(
	method string,
	endpoint string,
) *RequestBuilder

NewRequest creates a request builder.

func (*Client) Patch

func (c *Client) Patch(
	ctx context.Context,
	endpoint string,
	body any,
	marshaler Marshaler,
	headers map[string]string,
	queryParam map[string][]string,
	pathParams ...string,
) (res *http.Response, err error)

Patch runs an http PATCH request with all the given parameters.

func (*Client) Post

func (c *Client) Post(
	ctx context.Context,
	endpoint string,
	body any,
	marshaler Marshaler,
	headers map[string]string,
	queryParam map[string][]string,
	pathParams ...string,
) (res *http.Response, err error)

Post runs an http POST request with all the given parameters.

func (*Client) Put

func (c *Client) Put(
	ctx context.Context,
	endpoint string,
	body any,
	marshaler Marshaler,
	headers map[string]string,
	queryParam map[string][]string,
	pathParams ...string,
) (res *http.Response, err error)

Put runs an http PUT request with all the given parameters.

func (*Client) Use added in v0.2.0

func (c *Client) Use(
	statge MiddlewareStage,
	middlewares ...func(context.Context, *Request),
) error

Use attaches a middleware to the client's execution chain. Middlewares added before build run before the http.Request object is created from the http method, endpoint, headers, path query parameters and body. Middlewares added before execute run before the http.Request obeject is sent.

type Configuration

type Configuration struct {
	// contains filtered or unexported fields
}

Configuration is a collection of options that apply to the client.

type HttpClient

type HttpClient interface {
	Do(r *http.Request) (*http.Response, error)
}

HttpClient defines features of an internal http clients that is used to execute http requests.

type Marshaler

type Marshaler interface {
	Marshal(body any) (data []byte, content string, err error)
}

Marshaler defines how to convert an object into a byte array and its content type for making HTTP requests.

func NewFormMarshaler

func NewFormMarshaler() Marshaler

NewXMLMarshaler creates a marshaler for application/x-www-form-urlencoded content type.

func NewJSONMarshaler

func NewJSONMarshaler() Marshaler

NewJSONMarshaler creates a marshaler for application/json content type.

func NewXMLMarshaler

func NewXMLMarshaler() Marshaler

NewXMLMarshaler creates a marshaler for application/xml content type.

type MemPool

type MemPool struct {
	// contains filtered or unexported fields
}

MemPool manages pooling memory allocations for reusing dyanmic memory.

func NewDefaultMemPool

func NewDefaultMemPool() *MemPool

NewDefaultMemPool creates a memory pool with default page and pool size.

func NewMemPool

func NewMemPool(
	pageSize int,
	poolSize int,
) *MemPool

NewMemPool creates a memory pool with a channel that provides byte arrays with the configured page size. The pool's channel has an upper limit of pool size.

func (*MemPool) Acquire

func (m *MemPool) Acquire() []byte

Acquire returns a byte array from the pool, or creates a new one if the pool is empty.

func (*MemPool) Release

func (c *MemPool) Release(mem ...[]byte)

Release resets and inserts byte arrays into the pool. If the pool's channel is full, the byte array is discarded.

type MemoryPool

type MemoryPool interface {
	Acquire() []byte
	Release(...[]byte)
}

MemoryPool defines a pool that can be used to acquire memory and release memory as byte arrays.

type MiddlewareStage added in v0.2.0

type MiddlewareStage int

MiddlewareStage enumerates the stage in the request where middlewares are attached. Middlewares can be added before the http.Request object is built, or before the http.Request object is sent.

const (
	MDW_BeforeBuild MiddlewareStage = iota
	MDW_BeforeExecute
)

type Option

type Option interface {
	Configure(c *Configuration)
}

Option defines objects that can change a Configuration.

func UseHttpClient

func UseHttpClient(client HttpClient) Option

UseHttpClient creates an option for setting the internal http client.

func UseHttpClientConstructor

func UseHttpClientConstructor(constr func() HttpClient) Option

UseHttpClientConstructor creates an option for setting the constructor to create a new http client for each request.

func UseMemoryPool

func UseMemoryPool(pool MemoryPool) Option

UseMemoryPool creates an option for setting the client's memory pool.

type Request

type Request struct {
	Values map[string]any

	// Before Build
	Format      string
	Method      string
	Body        any
	Marshaler   Marshaler
	Headers     map[string]string
	QueryParams map[string][]string
	PathParams  []string

	// Before Execute
	Endpoint []byte
	Data     []byte
	Request  *http.Request
	Response *http.Response

	Errors []error
	// contains filtered or unexported fields
}

Request stores details about the request

func (*Request) Error

func (r *Request) Error(err error)

Error inserts an error to the errors slice.

func (*Request) Get added in v0.2.0

func (r *Request) Get(key string) (val any, ok bool)

Get retrieves some value from the context's Values store by a key. The operation locks the context's mutex for thread safety.

func (*Request) Lock added in v0.2.0

func (r *Request) Lock()

Lock locks the mutex within the context

func (*Request) Next

func (r *Request) Next()

Next executes the next function on the function middleware on the request. If there are no more functions to call, it does nothing.

func (*Request) Set added in v0.2.0

func (r *Request) Set(key string, val any)

Set assigns some value to a key in the context's Values store. The operation locks the context's mutex for thread safety.

func (*Request) Unlock added in v0.2.0

func (r *Request) Unlock()

Unlock unlocks the mutex within the context

type RequestBuilder added in v0.2.0

type RequestBuilder struct {
	// contains filtered or unexported fields
}

RequestBuilder allows gradual creation of http requests with functions to attach a body, headers, query parameters and path parameters.

func (*RequestBuilder) Run added in v0.2.0

func (rb *RequestBuilder) Run(
	ctx context.Context,
) (res *http.Response, err error)

Run runs the request with the client that created the request builder.

func (*RequestBuilder) WithBody added in v0.2.0

func (rb *RequestBuilder) WithBody(
	body any,
	marshaler Marshaler,
) *RequestBuilder

WithBody adds a request body and a marshaler to the request builder. If the request builder already has a request body and marshaler, they get overwritten.

func (*RequestBuilder) WithHeader added in v0.2.0

func (rb *RequestBuilder) WithHeader(
	key string,
	val string,
) *RequestBuilder

WithHeader adds a header to the request builder. If the key was already assigned some value, it gets overwritten.

func (*RequestBuilder) WithHeaders added in v0.2.0

func (rb *RequestBuilder) WithHeaders(
	headers map[string]string,
) *RequestBuilder

WithHeaders adds a list of headers to the request builder. If any of the keys was already assigned some value, it gets overwritten.

func (*RequestBuilder) WithPathParameters added in v0.2.0

func (rb *RequestBuilder) WithPathParameters(
	pathParams ...string,
) *RequestBuilder

WithPathParameter adds a path parameter to the request builder. Each parameter gets appended to the list in the builder.

func (*RequestBuilder) WithQueryParameter added in v0.2.0

func (rb *RequestBuilder) WithQueryParameter(
	key string,
	val []string,
) *RequestBuilder

WithQueryParameter adds a query parameter to the request builder. If the key was already assigned some value, it gets overwritten.

func (*RequestBuilder) WithQueryParameters added in v0.2.0

func (rb *RequestBuilder) WithQueryParameters(
	queryParams map[string][]string,
) *RequestBuilder

WithQueryParameters adds a list of query parameters to the request builder. If any of the keys was already assigned some value, it gets overwritten.

Jump to

Keyboard shortcuts

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