Documentation
¶
Overview ¶
Package httputil provides utilities for building HTTP clients and servers.
Package httputil provides utilities for working with HTTP servers and clients.
Package httputil provides utilities for working with HTTP servers and clients.
Index ¶
- func BindValidParameters(r *http.Request, output any) error
- func NewHandler[D, P any](action Action[D, P], options ...HandlerOption) http.Handler
- func WrapNetHTTPHandler(h http.Handler) http.Handler
- func WrapNetHTTPHandlerFunc(h http.HandlerFunc) http.Handler
- type Action
- type Client
- func (c *Client) BasePath() string
- func (c *Client) Client() *http.Client
- func (c *Client) Close() error
- func (c *Client) Delete(ctx context.Context, path string, options ...RequestOption) (*Result, error)
- func (c *Client) Do(req *http.Request) (*http.Response, error)
- func (c *Client) Get(ctx context.Context, path string, options ...RequestOption) (*Result, error)
- func (c *Client) Patch(ctx context.Context, path string, body any, options ...RequestOption) (*Result, error)
- func (c *Client) Post(ctx context.Context, path string, body any, options ...RequestOption) (*Result, error)
- func (c *Client) Put(ctx context.Context, path string, body any, options ...RequestOption) (*Result, error)
- type ClientCodec
- type ClientOption
- func WithClientBasePath(basePath string) ClientOption
- func WithClientCodec(codec ClientCodec) ClientOption
- func WithClientCookieJar(jar http.CookieJar) ClientOption
- func WithClientInterceptor(intercept InterceptorFunc) ClientOption
- func WithClientRedirectPolicy(policy RedirectPolicy) ClientOption
- func WithClientTimeout(timeout time.Duration) ClientOption
- type Endpoint
- type EndpointGroup
- type Guard
- type GuardFunc
- type GuardStack
- type HandlerOption
- type InterceptorFunc
- type InvalidOutputTypeError
- type JSONClientCodec
- type JSONServerCodec
- type MiddlewareFunc
- type ParamConversionError
- type RedirectPolicy
- type Request
- type RequestData
- type RequestEmpty
- type RequestOption
- type RequestParams
- type Response
- func Accepted(data any) (*Response, error)
- func Created(data any) (*Response, error)
- func NewResponse(code int, data any) *Response
- func NoContent() (*Response, error)
- func NothingToHandle() (*Response, error)
- func OK(data any) (*Response, error)
- func Redirect(code int, url string) (*Response, error)
- type Result
- type RoundTripperFunc
- type Server
- type ServerCodec
- type ServerOption
- func WithServerAddress(address string) ServerOption
- func WithServerCodec(codec ServerCodec) ServerOption
- func WithServerIdleTimeout(timeout time.Duration) ServerOption
- func WithServerMaxBodySize(size int64) ServerOption
- func WithServerReadHeaderTimeout(timeout time.Duration) ServerOption
- func WithServerReadTimeout(timeout time.Duration) ServerOption
- func WithServerShutdownTimeout(timeout time.Duration) ServerOption
- func WithServerWriteTimeout(timeout time.Duration) ServerOption
- type Transformer
- type UnsupportedFieldTypeError
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func BindValidParameters ¶
BindValidParameters extracts parameters from an *http.Request, populates the fields of the output struct, and validates the struct. The output parameter must be a pointer to a struct, and the struct fields can be annotated with struct tags to specify the source of the parameters. Supported struct tags and their meanings are:
- `query`: Specifies a query parameter to extract from the URL. - `header`: Specifies an HTTP header to extract from the request. - `path`: Specifies a path parameter to extract. Requires an implementation of r.PathValue(). - `default`: Provides a default value for the parameter if it's not found in the request. - `validate`: Provides rules for the validator.
Example:
type Params struct {
Sort string `query:"user_id" validate:"required"`
AuthToken string `header:"Authorization"`
Page int `query:"page" default:"1"`
IsActive bool `query:"is_active" default:"false"`
ID uuid.UUID `path:"id"`
}
var params Params
if err := BindValidParameters(r, ¶ms); err != nil {
return fmt.Errorf("failed to unmarshal params: %v", err)
}
If a field's type is unsupported, or if a value cannot be converted to the target type, a descriptive error is returned. Supported field types include:
- string - int - bool - float64 - uuid.UUID
Returns problem.BadParameters if: - A value cannot be converted to the target field type. - Validation fails.
Returns an error if: - `output` is not a pointer to a struct. - A default value cannot be converted to the target field type. - A field type in the struct is unsupported.
func NewHandler ¶ added in v0.2.0
func NewHandler[D, P any](action Action[D, P], options ...HandlerOption) http.Handler
NewHandler creates a new Handler that wraps the provided Action. It accepts options to configure the handler's behavior.
func WrapNetHTTPHandler ¶ added in v0.2.0
WrapNetHTTPHandler wraps a standard http.Handler with additional functionality like optional guard and logging.
func WrapNetHTTPHandlerFunc ¶ added in v0.2.0
func WrapNetHTTPHandlerFunc(h http.HandlerFunc) http.Handler
WrapNetHTTPHandlerFunc wraps an http.HandlerFunc in a netHTTPHandler to support additional features like guarding and logging.
Types ¶
type Action ¶
Action defines the interface for an action function that will be called by the handler. It takes a Request that has data of type D and params of type P and returns a Response or an error.
type Client ¶ added in v0.2.0
type Client struct {
// contains filtered or unexported fields
}
Client is an HTTP client that wraps a standard http.Client and provides convenience methods for making requests and handling responses.
func NewClient ¶ added in v0.2.0
func NewClient(options ...ClientOption) *Client
NewClient creates a new Client with the given options.
func (*Client) Close ¶ added in v0.2.0
Close closes any connections on its http.Client.Transport which were previously connected from previous requests but are now sitting idle in a "keep-alive" state. It does not interrupt any connections currently in use. See the http.Client.CloseIdleConnections documentation for details.
If http.Client.Transport does not have a http.Client.CloseIdleConnections method then this method does nothing. Interestingly, the http.Client type does not implement the io.Closer interface. WithClientInterceptor wraps the http.Client.Transport to ensure that the CloseIdleConnections method is called.
func (*Client) Delete ¶ added in v0.2.0
func (c *Client) Delete(ctx context.Context, path string, options ...RequestOption) (*Result, error)
Delete sends an HTTP DELETE request to the specified path. It returns a Result which wraps the http.Response, or an error.
func (*Client) Do ¶ added in v0.2.0
Do executes the provided request using the Client's underlying *http.Client. It returns the raw *http.Response and an error, if any.
func (*Client) Get ¶ added in v0.2.0
Get sends an HTTP GET request to the specified path. It returns a Result which wraps the http.Response, or an error.
func (*Client) Patch ¶ added in v0.2.0
func (c *Client) Patch(ctx context.Context, path string, body any, options ...RequestOption) (*Result, error)
Patch sends an HTTP PATCH request to the specified path with the given body. It returns a Result which wraps the http.Response, or an error.
type ClientCodec ¶ added in v0.2.0
type ClientCodec interface {
// ContentType returns the Content-Type header value for the client codec.
ContentType() string
// Encode encodes the given data into a new io.Reader.
Encode(data any) (io.Reader, error)
// Decode reads and decodes the response body into the provided target struct
Decode(r io.Reader, into any) error
}
ClientCodec is an interface for encoding and decoding HTTP request and response bodies for the client. It provides methods for encoding request data and decoding response data or errors.
type ClientOption ¶ added in v0.2.0
type ClientOption func(co *clientOptions)
ClientOption allows default doer config values to be overridden.
func WithClientBasePath ¶ added in v0.2.0
func WithClientBasePath(basePath string) ClientOption
WithClientBasePath sets the base path for the Client. This is used to prefix relative paths in the request URLs.
func WithClientCodec ¶ added in v0.2.0
func WithClientCodec(codec ClientCodec) ClientOption
WithClientCodec sets the ClientCodec that the Client will use when making requests.
func WithClientCookieJar ¶ added in v0.2.0
func WithClientCookieJar(jar http.CookieJar) ClientOption
WithClientCookieJar sets the CookieJar that the Client will use when making requests.
func WithClientInterceptor ¶ added in v0.2.0
func WithClientInterceptor(intercept InterceptorFunc) ClientOption
WithClientInterceptor adds an InterceptorFunc to the Client. Each InterceptorFunc will be executed in the order that it was added.
func WithClientRedirectPolicy ¶ added in v0.2.0
func WithClientRedirectPolicy(policy RedirectPolicy) ClientOption
WithClientRedirectPolicy sets the RedirectPolicy that the Client will use when following redirects.
func WithClientTimeout ¶ added in v0.2.0
func WithClientTimeout(timeout time.Duration) ClientOption
WithClientTimeout sets the timeout for the doer. This is the maximum amount of time the doer will wait for a response from the server.
type Endpoint ¶
type Endpoint struct {
// Method is the HTTP method for this endpoint (e.g., "GET", "POST", "PUT",
// "DELETE").
Method string
// Path is the URL path for this endpoint (e.g., "/users", "/products/{id}").
Path string
// Handler is the [http.Handler] that will handle requests for this endpoint.
Handler http.Handler
// contains filtered or unexported fields
}
Endpoint represents an HTTP endpoint with a method, path, and handler.
func NewEndpointWithGuard ¶ added in v0.2.0
NewEndpointWithGuard associates the given Guard with the specified Endpoint. It returns a new Endpoint with the Guard applied. The original Endpoint remains unmodified.
type EndpointGroup ¶
type EndpointGroup []Endpoint
EndpointGroup represents a group of Endpoint definitions allowing access to helper functions to define the group.
func (EndpointGroup) WithGuard ¶ added in v0.2.0
func (eg EndpointGroup) WithGuard(g Guard) EndpointGroup
WithGuard adds the Guard as a GuardStack with the currently set Guard as the second Guard in the stack. It returns a new slice of EndpointGroup with the Guard set. The original endpoints are not modified.
func (EndpointGroup) WithMiddleware ¶
func (eg EndpointGroup) WithMiddleware(middleware MiddlewareFunc) EndpointGroup
WithMiddleware applies the given middleware to all provided endpoints. It returns a new slice of EndpointGroup with the middleware applied to their handlers. The original endpoints are not modified.
func (EndpointGroup) WithPrefix ¶
func (eg EndpointGroup) WithPrefix(prefix string) EndpointGroup
WithPrefix prefixes the given path to all provided endpoints. It returns a new slice of EndpointGroup with the prefixed paths. The original endpoints are not modified.
type Guard ¶ added in v0.2.0
Guard defines an interface for components that protect access to a Handler's Action. It acts as a crucial pre-processing gatekeeper within the handler's request lifecycle, executing after the request has been routed to the handler, but *before* any automatic request body decoding or parameter binding occurs.
Its primary role is to enforce preconditions, such as authentication, authorization, API key validation, or other checks based on request headers, context, or basic properties, before allowing the request to proceed to the core business logic (the Action).
type GuardFunc ¶ added in v0.2.0
GuardFunc is a function type for modifying or inspecting an HTTP request, potentially returning an altered request. This is useful for authentication and adding claims to the request context.
type GuardStack ¶ added in v0.2.0
type GuardStack []Guard
GuardStack represents multiple Guard instances that will be run in order.
type HandlerOption ¶ added in v0.2.0
type HandlerOption func(ho *handlerOptions)
HandlerOption allows default handler config values to be overridden.
func WithHandlerCodec ¶ added in v0.2.0
func WithHandlerCodec(codec ServerCodec) HandlerOption
WithHandlerCodec sets the ServerCodec that the Handler will use when NewHandler is called.
func WithHandlerGuard ¶ added in v0.2.0
func WithHandlerGuard(guard Guard) HandlerOption
WithHandlerGuard sets the Guard that the Handler will use when NewHandler is called.
func WithHandlerLogger ¶ added in v0.2.0
func WithHandlerLogger(logger *slog.Logger) HandlerOption
WithHandlerLogger sets the slog.Logger that the Handler will use when NewHandler is called.
type InterceptorFunc ¶ added in v0.2.0
type InterceptorFunc func(next http.RoundTripper) http.RoundTripper
InterceptorFunc defines a function type for HTTP client middleware. An InterceptorFunc takes an http.RoundTripper as input and returns a new http.RoundTripper that wraps the original action with additional logic.
type InvalidOutputTypeError ¶
type InvalidOutputTypeError struct {
ProvidedType any
}
InvalidOutputTypeError is a custom error type for invalid output types.
func (*InvalidOutputTypeError) Error ¶
func (e *InvalidOutputTypeError) Error() string
Error returns the error message describing the provided invalid output type.
type JSONClientCodec ¶ added in v0.2.0
type JSONClientCodec struct{}
JSONClientCodec provides methods to encode data as JSON or decode data from JSON in HTTP requests and responses.
func NewJSONClientCodec ¶ added in v0.2.0
func NewJSONClientCodec() JSONClientCodec
NewJSONClientCodec creates a new JSONClientCodec instance.
func (JSONClientCodec) ContentType ¶ added in v0.2.0
func (c JSONClientCodec) ContentType() string
ContentType returns the Content-Type header value for JSON requests and responses.
type JSONServerCodec ¶ added in v0.2.0
type JSONServerCodec struct{}
JSONServerCodec provides methods to encode data as JSON or decode data from JSON in HTTP requests and responses.
func NewJSONServerCodec ¶ added in v0.2.0
func NewJSONServerCodec() JSONServerCodec
NewJSONServerCodec creates a new JSONServerCodec instance.
func (JSONServerCodec) Decode ¶ added in v0.2.0
func (c JSONServerCodec) Decode(r *http.Request, into any) error
Decode reads and decodes the JSON body of an HTTP request into the provided target struct or variable. Returns an error if decoding fails or if the request body is nil.
func (JSONServerCodec) Encode ¶ added in v0.2.0
func (c JSONServerCodec) Encode(w http.ResponseWriter, data any) error
Encode writes the given data as JSON to the provided HTTP response writer with the appropriate Content-Type header.
func (JSONServerCodec) EncodeError ¶ added in v0.2.0
func (c JSONServerCodec) EncodeError(w http.ResponseWriter, err error) error
EncodeError encodes an error into an HTTP response, handling `problem.DetailedError` if applicable to set the correct content type, or falling back to standard JSON encoding otherwise.
type MiddlewareFunc ¶
MiddlewareFunc defines a function type for HTTP server middleware. A MiddlewareFunc takes a http.Handler as input and returns a new http.Handler that wraps the original action with additional logic.
type ParamConversionError ¶
type ParamConversionError struct {
ParameterType problem.ParameterType
ParamName string
TargetType string
Err error
}
ParamConversionError represents an error that occurs during parameter conversion.
func (*ParamConversionError) Error ¶
func (e *ParamConversionError) Error() string
Error satisfies the error interface for ParamConversionError.
func (*ParamConversionError) Unwrap ¶
func (e *ParamConversionError) Unwrap() error
Unwrap allows ParamConversionError to be used with errors.Is and errors.As.
type RedirectPolicy ¶ added in v0.2.0
RedirectPolicy defines the policy for handling HTTP redirects.
type Request ¶
type Request[D, P any] struct { *http.Request // Data holds the request-specific data of generic type D, which is provided // when initializing the request. A [Handler] will attempt to decode the http.Request // body into this type. Data D // Params holds the parameters of generic type P associated with the request, // allowing dynamic decoding and validation of Request parameters. See // [BindValidParameters] documentation for usage information. Params P // ResponseWriter is an embedded HTTP response writer used to construct and send // the HTTP response. When writing a response via the ResponseWriter directly, it // is best practice to return a [NothingToHandle] response so that the handler // does not try to encode response data or handle errors. ResponseWriter http.ResponseWriter }
Request is a generic HTTP request wrapper that contains request data, parameters, and a response writer.
type RequestData ¶
RequestData represents a Request that expects data but no Params. It's a type alias for Request with a generic data type D and an empty struct for Params. Use this type when your handler needs to process request body data but doesn't need URL parameters.
type RequestEmpty ¶
type RequestEmpty = Request[struct{}, struct{}]
RequestEmpty represents an empty Request that expects no Params or data. It's a type alias for Request with empty structs for both data and Params. Use this type when your handler doesn't need to process any request body or URL parameters.
type RequestOption ¶ added in v0.2.0
type RequestOption func(ro *requestOptions)
RequestOption allows default request config values to be overridden.
func WithRequestHeader ¶ added in v0.2.0
func WithRequestHeader(k, v string) RequestOption
WithRequestHeader adds a header to the request.
func WithRequestHeaders ¶ added in v0.2.0
func WithRequestHeaders(headers map[string]string) RequestOption
WithRequestHeaders adds multiple headers to the request.
func WithRequestParam ¶ added in v0.2.0
func WithRequestParam(k, v string) RequestOption
WithRequestParam adds a query parameter to the request.
func WithRequestParams ¶ added in v0.2.0
func WithRequestParams(params map[string]string) RequestOption
WithRequestParams adds multiple query parameters to the request.
type RequestParams ¶
RequestParams represents a Request that expects Params but no data. It's a type alias for Request with an empty struct for data and a generic Params type P. Use this type when your handler needs to process URL parameters but doesn't need request body data.
type Response ¶
type Response struct {
// contains filtered or unexported fields
}
Response represents an HTTP response that holds optional data and the required information to write a response.
func Accepted ¶
Accepted creates a new Response object with a status code of http.StatusAccepted (202 Accepted) and the given data.
func Created ¶
Created creates a new Response object with a status code of http.StatusCreated (201 Created) and the given data.
func NewResponse ¶
NewResponse creates a new Response object with the given status code and data.
func NoContent ¶
func NoContent() (*Response, error)
NoContent creates a new Response object with a status code of http.StatusNoContent (204 No Content) and an empty struct as data.
func NothingToHandle ¶
func NothingToHandle() (*Response, error)
NothingToHandle returns a nil Response and a nil error, intentionally representing a scenario with no response output so the Handler does not attempt to process a response. This adds clarity when a Guard does not block the request or when acting on Request.ResponseWriter directly.
type Result ¶ added in v0.2.0
Result wraps an http.Response and provides convenience methods for decoding the response body and checking status codes.
func (*Result) AsProblemDetails ¶ added in v0.2.0
func (r *Result) AsProblemDetails() (*problem.DetailedError, error)
AsProblemDetails attempts to decode the response body into a problem.DetailedError. This is useful for handling API errors that conform to RFC 7807.
Note: This method consumes the response body. Subsequent calls to Decode or AsProblemDetails will fail if the body has already been read.
func (*Result) Decode ¶ added in v0.2.0
Decode decodes the response body into the provided target. It uses the ClientCodec to perform the decoding.
Note: This method consumes the response body. Subsequent calls to Decode or AsProblemDetails will fail if the body has already been read.
type RoundTripperFunc ¶ added in v0.2.0
RoundTripperFunc is an adapter to allow the use of ordinary functions as http.RoundTripper. If f is a function with the appropriate signature, RoundTripperFunc(f) is a http.RoundTripper that calls f.
type Server ¶
type Server struct {
// Listener is implemented by a *http.Server, the interface allows us to test Serve.
Listener interface {
ListenAndServe() error
Shutdown(ctx context.Context) error
}
// contains filtered or unexported fields
}
Server is an HTTP server with graceful shutdown capabilities.
func NewServer ¶
func NewServer(logger *slog.Logger, options ...ServerOption) *Server
NewServer creates a new Server instance with the specified logger and options. The options allow for customization of server settings such as the address, codec, and timeouts.
func (*Server) Register ¶
Register one or more endpoints with the Server so they are handled by the underlying router.
type ServerCodec ¶ added in v0.2.0
type ServerCodec interface {
// Decode decodes the request data and sets it on into. Implementations of
// Decode should return [io.EOF] if the request data is empty when Decode is
// called.
Decode(r *http.Request, into any) error
// Encode writes the given data to the http.ResponseWriter after encoding it,
// returning an error if encoding fails.
Encode(w http.ResponseWriter, data any) error
// EncodeError encodes the provided error into the HTTP response writer and
// returns an error if encoding fails.
EncodeError(w http.ResponseWriter, err error) error
}
ServerCodec is an interface for encoding and decoding HTTP requests and responses. It provides methods for decoding request data and encoding response data or errors.
type ServerOption ¶
type ServerOption func(so *serverOptions)
ServerOption allows default server config values to be overridden.
func WithServerAddress ¶ added in v0.2.0
func WithServerAddress(address string) ServerOption
WithServerAddress sets the address that the Server will listen to and serve on.
func WithServerCodec ¶ added in v0.2.0
func WithServerCodec(codec ServerCodec) ServerOption
WithServerCodec sets the ServerCodec that the Server will use by default when NewHandler is called.
func WithServerIdleTimeout ¶ added in v0.2.0
func WithServerIdleTimeout(timeout time.Duration) ServerOption
WithServerIdleTimeout sets the idle timeout for the server. This determines how long the server will keep an idle connection alive.
func WithServerMaxBodySize ¶ added in v0.2.0
func WithServerMaxBodySize(size int64) ServerOption
WithServerMaxBodySize sets the maximum allowed size for the request body. This limit helps prevent excessive memory usage or abuse from clients sending extremely large payloads.
func WithServerReadHeaderTimeout ¶ added in v0.2.0
func WithServerReadHeaderTimeout(timeout time.Duration) ServerOption
WithServerReadHeaderTimeout sets the timeout for reading the request header. This is the maximum amount of time the server will wait to receive the request headers.
func WithServerReadTimeout ¶ added in v0.2.0
func WithServerReadTimeout(timeout time.Duration) ServerOption
WithServerReadTimeout sets the timeout for reading the request body. This is the maximum amount of time the server will wait for the entire request to be read.
func WithServerShutdownTimeout ¶ added in v0.2.0
func WithServerShutdownTimeout(timeout time.Duration) ServerOption
WithServerShutdownTimeout sets the timeout for gracefully shutting down the server. This is the amount of time the server will wait for existing connections to complete before shutting down.
func WithServerWriteTimeout ¶ added in v0.2.0
func WithServerWriteTimeout(timeout time.Duration) ServerOption
WithServerWriteTimeout sets the timeout for writing the response. This is the maximum amount of time the server will wait to send a response.
type Transformer ¶
Transformer allows for operations to be performed on the Request, Response or Params data before it gets finalized. A Transformer will not be called for a standard http.Handler as there is nothing to transform.
type UnsupportedFieldTypeError ¶
type UnsupportedFieldTypeError struct {
FieldType any
}
UnsupportedFieldTypeError represents an error for unsupported field types.
func (*UnsupportedFieldTypeError) Error ¶
func (e *UnsupportedFieldTypeError) Error() string
Error satisfies the error interface for UnsupportedFieldTypeError.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
testutil
Package testutil provides helper functions for writing tests.
|
Package testutil provides helper functions for writing tests. |
|
Package problem provides utilities for constructing and handling error responses in accordance with RFC 9457 (Problem Details for HTTP APIs).
|
Package problem provides utilities for constructing and handling error responses in accordance with RFC 9457 (Problem Details for HTTP APIs). |
|
problemtest
Package problemtest provides utilities for creating and testing problems.
|
Package problemtest provides utilities for creating and testing problems. |