gent

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: May 25, 2025 License: MIT Imports: 10 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.

Usage

A Client allows you to make HTTP requests. Use NewDefaultClient to create one using http.DefaultClient, or NewClient to provide anything that implements the Requester interface. Client implements the same methods as the net/http Client to make requests.

//  type Requester interface {
//      Do(*http.Request) (*http.Response, error)
//      CloseIdleConnections()
//  }

cl := gent.NewClient(http.DefaultClient)

// simple get request
res, err := cl.Get("https://localhost:8080")
if err != nil {
    panic(err)
}

// complex patch request
body := bytes.NewBuffer([]byte(`{"name": "John Smith"}`))
req, err := http.NewRequest(http.MethodPatch, "https://localhost:8080", body)
if err != nil {
    panic(err)
}

req.Header.Set("Content-Type", "application/json")

res, err = cl.Do(req)
if err != nil {
    panic(err)
}
Request Builder

A RequestBuilder assists in creating an *http.Request by providing a series of chainable functions, placeholders and body marshaling.

obj := map[string]string{
    "id": "4481e035-1711-419f-82bc-bfb72da06375",
    "name": "John Smith",
}

// regular
rb := gent.NewRequest(http.MethodPost, "http://localhost:8080/{}/{}")
rb.WithBody(obj, gent.JsonMarshaler)
rb.WithHeader("Authorization", "Bearer x.y.z",)
rb.WithQueryParameter("strict", []string{"true"})
rb.WithPathParameters("employees", "create")
req, err := rb.Build(context.Background())

// chained
req, err := gent.NewRequest(
    http.MethodPost, "http://localhost:8080/{}/{}",
).WithBody(
    obj, gent.JsonMarshaler,
).WithHeader(
    "Authorization", "Bearer x.y.z",
).WithQueryParameter(
    "strict", []string{"true"},
).WithPathParameters(
    "employees", "create",
).Build(context.Background())
Placeholders

The request's format supports placeholders in the form of {}. Placeholders will be replaced by encoded path parameters in the order they were provided.

Request Body

Any object can be provided as a request body along with a marshaler that will encode the object and attach some optional headers to the request. The package provides JSON, XML and URL-Encoded Form marshalers, but any function with the signature func(any) ([]byte, map[string][]string, error) is a valid marshaler.

// JsonMarshaler uses the standard encoding/json marshaler to return the
// json encoded body and a Content-Type application/json header.
func JsonMarshaler(body any) (dat []byte, hdrs map[string][]string, err error) {
	hdrs = map[string][]string{"Content-Type": {"application/json"}}
	dat, err = json.Marshal(body)
	return
}
Middlewares

A Client can use middleware-style functions that extend its behavior when making requests. Middleware functions run in the order they were attached, and the last function performs the request. Each function has a request context to pass data between middlewares, or to interact with the request or response. Use the Next() method on the context to move to the next middleware.

cl := gent.NewClient()

cl.Use(
    func(r *gent.Context) {
        now := time.Now()
        r.Next()
        fmt.Println("Elapsed time: ", time.Since(now))
    },
)

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrInvalidBodyType = errors.New("invalid body type")

ErrInvalidBodyType is returned by Marshaler functions when the object can not be marshaled into a byte array due to its type, or the RequestBuilder when the body requires a marshaler but none is provided

View Source
var ErrInvalidFormat = errors.New("invalid endpoint format")

ErrInvalidFormat is returned by RequestBuilder.Build when the format has a trailing or incomplate placeholder {}, or if the number of placeholders does not match the number of path parameters

Functions

func JsonMarshaler added in v0.3.0

func JsonMarshaler(body any) (dat []byte, hdrs map[string][]string, err error)

JsonMarshaler uses the standard encoding/json marshaler to return the json encoded body and a Content-Type application/json header.

func UrlEncodedMarshaler added in v0.3.0

func UrlEncodedMarshaler(body any) (dat []byte, hdrs map[string][]string, err error)

UrlEncodedMarshaler uses the standard net/url encoder to return the url encoded body and a Content-Type application/x-www-form-urlencoded header.

func XmlMarshaler added in v0.3.0

func XmlMarshaler(body any) (dat []byte, hdrs map[string][]string, err error)

XmlMarshaler uses the standard encoding/xml marshaler to return the xml encoded body and a Content-Type application/xml header.

Types

type Client

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

Client wraps an http Client with additional features.

func NewClient

func NewClient(client Requester) *Client

NewClient creates a Client from the provided Requester.

func NewDefaultClient added in v0.3.0

func NewDefaultClient() *Client

NewDefaultClient creates a Client from http.DefaultClient.

func (*Client) CloseIdleConnections added in v0.3.0

func (c *Client) CloseIdleConnections()

CloseIdleConnections closes idle connections on the underlying Requester.

func (*Client) Do

func (c *Client) Do(
	req *http.Request,
) (res *http.Response, err error)

Do sends an HTTP request and returns an HTTP response.

func (*Client) Get

func (c *Client) Get(
	url string,
) (res *http.Response, err error)

Get sends a GET HTTP request to the specified URL.

func (*Client) Head added in v0.3.0

func (c *Client) Head(
	url string,
) (res *http.Response, err error)

Head sends a HEAD HTTP request to the specified URL.

func (*Client) Post

func (c *Client) Post(
	url string,
	contentType string,
	body io.Reader,
) (res *http.Response, err error)

Post sends a POST HTTP request to the specified URL with a content type header and a request body.

func (*Client) PostForm added in v0.3.0

func (c *Client) PostForm(
	url string,
	data url.Values,
) (res *http.Response, err error)

PostForm sends a POST HTTP request to the specified URL with a content type header of application/x-www-form-urlencoded and url encoded values as the request body.

func (*Client) Use added in v0.2.0

func (c *Client) Use(
	middlewares ...func(*Context),
)

Use adds a middleware style handler function to the execution chain of the requests performed by the client which run in the order they were added before the client performs the request.

type Context added in v0.3.0

type Context struct {
	Request  *http.Request
	Response *http.Response
	Values   map[string]any
	Errors   []error
	// contains filtered or unexported fields
}

Context stores details about a request. It does not implement context.Context.

func (*Context) Del added in v0.3.0

func (ctx *Context) Del(key string)

Del removes some value from the context's store by a key. The operation locks the context's mutex for thread safety.

func (*Context) Error added in v0.3.0

func (ctx *Context) Error(err error)

Error appends an error to the context.

func (*Context) Get added in v0.3.0

func (ctx *Context) Get(key string) (val any, ok bool)

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

func (*Context) Lock added in v0.3.0

func (ctx *Context) Lock()

Lock locks the mutex in the context.

func (*Context) Next added in v0.3.0

func (ctx *Context) Next()

Next runs the next middleware function on the context. If there are no more functions, it does nothing.

func (*Context) Set added in v0.3.0

func (ctx *Context) Set(key string, val any)

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

func (*Context) Unlock added in v0.3.0

func (ctx *Context) Unlock()

Unlock unlocks the mutex in the context.

type Marshaler

type Marshaler func(body any) ([]byte, map[string][]string, error)

Marshaler defines how to process an object into byte array for a request's body, with additional optional headers to set.

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 NewRequest added in v0.3.0

func NewRequest(
	method string,
	format string,
) *RequestBuilder

NewRequest creates a request builder.

func (*RequestBuilder) Build added in v0.3.0

func (rb *RequestBuilder) Build(
	ctx context.Context,
) (res *http.Request, err error)

Build returns a *http.Request from the values of the request builder.

func (*RequestBuilder) WithBody added in v0.2.0

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

WithBody adds a body and a marshaler to the request. If a body or marshaler is already set, it will overwrite it. The headers returned by the marshaler will not overwrite headers set by [WithHeader] or [WithHeaders]

func (*RequestBuilder) WithHeader added in v0.2.0

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

WithHeader adds a header to the request. If there was already a header set with the same key, it will overwrite it.

func (*RequestBuilder) WithPathParameters added in v0.2.0

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

WithPathParameter adds path parameters to the request. The parameters get escaped and appended to the list in the request builder. Path parameters replace {} placeholders in the request endpoint in the order they were added.

func (*RequestBuilder) WithQueryParameter added in v0.2.0

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

WithQueryParameter adds a query parameter to the request. If there was already a parameter set with the same key, it will overwrite it.

func (*RequestBuilder) WithRawBody added in v0.3.0

func (rb *RequestBuilder) WithRawBody(
	body []byte,
) *RequestBuilder

WithRawBody sets a byte array as the request body. If a body or marshaler is already set, it will overwrite it.

type Requester added in v0.3.0

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

Requester defines an HTTP client that can do requests.

Jump to

Keyboard shortcuts

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