httputil

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2023 License: Apache-2.0 Imports: 14 Imported by: 1

Documentation

Overview

Package pagination provides support for pagination requests and responses.

Index

Constants

This section is empty.

Variables

View Source
var (
	// DefaultPageSize specifies the default page size
	DefaultPageSize = 100
	// MaxPageSize specifies the maximum page size
	MaxPageSize = 1000
	// PageVar specifies the query parameter name for page number
	PageVar = "page"
	// PageSizeVar specifies the query parameter name for page size
	PageSizeVar = "per_page"
)

Functions

func QueryParam

func QueryParam[T ParamTypes, K FromConstraint](from K, param string, validators ...validator.Validator[T]) (T, error)

func QueryParamOrDefault

func QueryParamOrDefault[T ParamTypes, K FromConstraint](from K, param string, defValue T, validators ...validator.Validator[T]) T

Types

type Chain

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

Chain acts as a list of http.Handler constructors. Chain is effectively immutable: once created, it will always hold the same set of constructors in the same order.

func NewChain

func NewChain(constructors ...Constructor) Chain

NewChain creates a new chain, memorizing the given list of middleware constructors. New serves no other function, constructors are only called upon a call to Then().

func (Chain) Append

func (c Chain) Append(constructors ...Constructor) Chain

Append extends a chain, adding the specified constructors as the last ones in the request flow.

Append returns a new chain, leaving the original one untouched.

stdChain := httputil.NewChain(m1, m2)
extChain := stdChain.Append(m3, m4)
// requests in stdChain go m1 -> m2
// requests in extChain go m1 -> m2 -> m3 -> m4

func (Chain) Extend

func (c Chain) Extend(chain Chain) Chain

Extend extends a chain by adding the specified chain as the last one in the request flow.

Extend returns a new chain, leaving the original one untouched.

stdChain := httputil.NewChain(m1, m2)
ext1Chain := httputil.NewChain(m3, m4)
ext2Chain := stdChain.Extend(ext1Chain)
// requests in stdChain go  m1 -> m2
// requests in ext1Chain go m3 -> m4
// requests in ext2Chain go m1 -> m2 -> m3 -> m4

Another example:

 aHtmlAfterNosurf := httputil.NewChain(m2)
	aHtml := httputil.NewChain(m1, func(h http.Handler) http.Handler {
		csrf := nosurf.New(h)
		csrf.SetFailureHandler(aHtmlAfterNosurf.ThenFunc(csrfFail))
		return csrf
	}).Extend(aHtmlAfterNosurf)
		// requests to aHtml hitting nosurfs success handler go m1 -> nosurf -> m2 -> target-handler
		// requests to aHtml hitting nosurfs failure handler go m1 -> nosurf -> m2 -> csrfFail

func (Chain) Then

func (c Chain) Then(h http.Handler) http.Handler

Then chains the middleware and returns the final http.Handler.

New(m1, m2, m3).Then(h)

is equivalent to:

m1(m2(m3(h)))

When the request comes in, it will be passed to m1, then m2, then m3 and finally, the given handler (assuming every middleware calls the following one).

A chain can be safely reused by calling Then() several times.

stdStack := httputil.NewChain(ratelimitHandler, csrfHandler)
indexPipe = stdStack.Then(indexHandler)
authPipe = stdStack.Then(authHandler)

Note that constructors are called on every call to Then() and thus several instances of the same middleware will be created when a chain is reused in this way. For proper middleware, this should cause no problems.

Then() treats nil as http.DefaultServeMux.

func (Chain) ThenFunc

func (c Chain) ThenFunc(fn http.HandlerFunc) http.Handler

ThenFunc works identically to Then, but takes a HandlerFunc instead of a Handler.

The following two statements are equivalent:

c.Then(http.HandlerFunc(fn))
c.ThenFunc(fn)

ThenFunc provides all the guarantees of Then.

type Client

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

func NewClient

func NewClient(uri string, options ...ClientOption) *Client

func (*Client) Delete

func (c *Client) Delete(ctx context.Context, rawurl string, options ...RequestOption) error

helper function for making an http DELETE request.

func (*Client) Get

func (c *Client) Get(ctx context.Context, rawurl string, out any, options ...RequestOption) error

helper function for making an http GET request.

func (*Client) Patch

func (c *Client) Patch(ctx context.Context, rawurl string, in, out any, options ...RequestOption) error

helper function for making an http PATCH request.

func (*Client) Post

func (c *Client) Post(ctx context.Context, rawurl string, in, out any, options ...RequestOption) error

helper function for making an http POST request.

func (*Client) SetClient

func (c *Client) SetClient(client *http.Client)

SetClient sets the default http client. This can be used in conjunction with golang.org/x/oauth2 to authenticate requests to the server.

func (*Client) SetDebug

func (c *Client) SetDebug(debug bool)

SetDebug sets the debug flag. When the debug flag is true, the http.Resposne body to stdout which can be helpful when debugging.

type ClientOption

type ClientOption interface {
	Apply(r *Client)
}

type ClientOptionFunc

type ClientOptionFunc func(c *Client)

func WithHTTPTimeout

func WithHTTPTimeout(timeout time.Duration) ClientOptionFunc

WithHTTPTimeout sets timeout

func (ClientOptionFunc) Apply

func (f ClientOptionFunc) Apply(c *Client)

type Constructor

type Constructor func(http.Handler) http.Handler

A constructor for a piece of middleware.

type ErrorResponse

type ErrorResponse struct {
	Status  int
	Payload string
}

func (ErrorResponse) Error

func (r ErrorResponse) Error() string

type FromConstraint

type FromConstraint interface {
	*http.Request | *url.URL | url.Values
}

type Pages

type Pages[T any] struct {
	Page       int `json:"page"`
	PerPage    int `json:"per_page"`
	PageCount  int `json:"page_count"`
	TotalCount int `json:"total_count"`
	Items      []T `json:"items"`
}

Pages represents a paginated list of data items.

func NewPages

func NewPages[T any](page, perPage, total int) *Pages[T]

NewPages creates a new Pages instance. The page parameter is 1-based and refers to the current page index/number. The perPage parameter refers to the number of items on each page. And the total parameter specifies the total number of data items. If total is less than 0, it means total is unknown.

func PagesFromRequest

func PagesFromRequest[T any](req *http.Request, count int) *Pages[T]

PagesFromRequest creates a Pages object using the query parameters found in the given HTTP request. count stands for the total number of items. Use -1 if this is unknown.

func (*Pages[T]) BuildLinkHeader

func (p *Pages[T]) BuildLinkHeader(baseURL string, defaultPerPage int) string

BuildLinkHeader returns an HTTP header containing the links about the pagination.

func (p *Pages[T]) BuildLinks(baseURL string, defaultPerPage int) [4]string

BuildLinks returns the first, prev, next, and last links corresponding to the pagination. A link could be an empty string if it is not needed. For example, if the pagination is at the first page, then both first and prev links will be empty.

func (*Pages[T]) Limit

func (p *Pages[T]) Limit() int

Limit returns the LIMIT value that can be used in a SQL statement.

func (*Pages[T]) Offset

func (p *Pages[T]) Offset() int

Offset returns the OFFSET value that can be used in a SQL statement.

type ParamTypes

type ParamTypes interface {
	~string | ~int | ~int64 | ~bool | ~float64 | time.Time |
		~[]string | ~[]int | ~[]int64 | ~[]bool | ~[]float64 | ~[]time.Time
}

type RequestOption

type RequestOption interface {
	Apply(r *http.Request)
}

type RequestOptionFunc

type RequestOptionFunc func(r *http.Request)

func WithAcceptVersion

func WithAcceptVersion(value string) RequestOptionFunc

func WithAuthHeader

func WithAuthHeader(value string) RequestOptionFunc

func (RequestOptionFunc) Apply

func (f RequestOptionFunc) Apply(r *http.Request)

Jump to

Keyboard shortcuts

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