Documentation
¶
Overview ¶
Package endpoint provides a high-level abstraction for building HTTP endpoints with automatic request/response handling, validation, and middleware support. It uses Go generics to create type-safe endpoint implementations.
Index ¶
- func ErrorHandler(logger log.Logger) http2.Middleware
- func MaxRequestBodySize(maxBytes int64) http2.Middleware
- func Metrics(storage *http_metrics.ServerStorage) http2.Middleware
- func New[Req any, Res any](fn func(ctx context.Context, req Req) (Res, error)) basic[Req, Res]
- func NewDefaultHttp(fn func(ctx context.Context, w http.ResponseWriter, r *http.Request) error) defaultHttp
- func NewWithRequest(fn func(ctx context.Context, r *http.Request) error) withRequest
- func NewWithoutResponse[Req any](fn func(ctx context.Context, req Req) error) withoutResponseBody[Req]
- func Recovery() http2.Middleware
- func RequestId() http2.Middleware
- type Caller
- type HttpError
- type JsonRequestExtractor
- type JsonResponseMapper
- type LogMiddleware
- type ParamBuilder
- type ParamMapper
- type RequestBodyExtractor
- type ResponseBodyMapper
- type Validator
- type Wrappable
- type Wrapper
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ErrorHandler ¶
func ErrorHandler(logger log.Logger) http2.Middleware
ErrorHandler is a middleware that logs errors and writes appropriate HTTP responses. It uses the error's logging level and enriches Sentry events with request details. For HttpError implementations, it writes the error using WriteError; otherwise, it returns a generic internal service error to hide implementation details.
func MaxRequestBodySize ¶
func MaxRequestBodySize(maxBytes int64) http2.Middleware
MaxRequestBodySize limits the size of the request body that can be read. It wraps the request body with http.MaxBytesReader to enforce the limit.
func Metrics ¶
func Metrics(storage *http_metrics.ServerStorage) http2.Middleware
Metrics is a middleware that collects HTTP server metrics for each endpoint. It records request duration, status code counts, and request/response body sizes. If the endpoint is not available in the context, it skips metrics collection.
func New ¶ added in v1.61.0
New creates a new generic endpoint with request and response types. The returned endpoint automatically handles JSON body extraction and response mapping.
func NewDefaultHttp ¶ added in v1.61.0
func NewDefaultHttp(fn func(ctx context.Context, w http.ResponseWriter, r *http.Request) error) defaultHttp
NewDefaultHttp creates an endpoint with direct access to ResponseWriter and Request. This is the most flexible option but bypasses automatic body extraction and mapping.
func NewWithRequest ¶ added in v1.61.0
NewWithRequest creates an endpoint that receives the raw http.Request. Use this when you need direct access to headers, query parameters, or other request details.
func NewWithoutResponse ¶ added in v1.61.0
func NewWithoutResponse[Req any](fn func(ctx context.Context, req Req) error) withoutResponseBody[Req]
NewWithoutResponse creates an endpoint that handles a request without returning a response body. Useful for operations like deletions or fire-and-forget actions.
func Recovery ¶
func Recovery() http2.Middleware
Recovery is a middleware that catches panics and converts them to errors. It ensures the server remains stable even when handler code panics. Safe for concurrent use.
func RequestId ¶
func RequestId() http2.Middleware
RequestId is a middleware that manages request IDs for tracing and logging. It uses the existing request ID from headers if present, or generates a new one. The request ID is added to the context and response headers.
Types ¶
type Caller ¶
type Caller struct {
// contains filtered or unexported fields
}
Caller uses reflection to wrap arbitrary functions as HTTP handlers. It automatically extracts request body, builds parameters from the context, and maps return values to the response.
func NewCaller ¶
func NewCaller( f any, bodyExtractor RequestBodyExtractor, bodyMapper ResponseBodyMapper, paramMappers map[string]ParamMapper, ) (*Caller, error)
NewCaller creates a new Caller that wraps the provided function. It analyzes the function signature and configures parameter extraction and result mapping. Returns an error if the provided value is not a function or has invalid parameter types.
type HttpError ¶
type HttpError interface {
WriteError(w http.ResponseWriter) error
}
HttpError is an interface for errors that can write themselves to an HTTP response. Implementations should handle their own HTTP status codes and response formatting.
type JsonRequestExtractor ¶
type JsonRequestExtractor struct {
Validator Validator
}
JsonRequestExtractor extracts and validates JSON request bodies. It decodes JSON, validates the result, and returns business errors for invalid input.
func (JsonRequestExtractor) Extract ¶
func (j JsonRequestExtractor) Extract(ctx context.Context, reader io.Reader, reqBodyType reflect.Type) (reflect.Value, error)
Extract decodes the JSON request body into a reflect.Value of the specified type. It validates the decoded value and returns a business error if validation fails.
type JsonResponseMapper ¶
type JsonResponseMapper struct {
}
JsonResponseMapper maps response objects to JSON format. It sets the Content-Type header to application/json and includes the request ID in response headers.
func (JsonResponseMapper) Map ¶
func (j JsonResponseMapper) Map(ctx context.Context, result any, w http.ResponseWriter) error
Map marshals the result to JSON and writes it to the http.ResponseWriter. It skips nil results and includes the request ID in the response headers if available.
type LogMiddleware ¶ added in v1.40.0
type LogMiddleware http2.Middleware
LogMiddleware is an alias for http.Middleware used for request/response logging.
type ParamBuilder ¶
ParamBuilder is a function that builds a parameter value from the request context.
type ParamMapper ¶
type ParamMapper struct {
// Type is the string representation of the parameter type.
Type string
// Builder creates the parameter value from the request context.
Builder ParamBuilder
}
ParamMapper maps a parameter type to its builder function.
func ContextParam ¶
func ContextParam() ParamMapper
ContextParam creates a ParamMapper that provides context.Context to endpoint functions. This is automatically included in the default wrapper.
func RequestParam ¶
func RequestParam() ParamMapper
RequestParam creates a ParamMapper that provides *http.Request to endpoint functions. This is automatically included in the default wrapper.
func ResponseWriterParam ¶
func ResponseWriterParam() ParamMapper
ResponseWriterParam creates a ParamMapper that provides http.ResponseWriter to endpoint functions. This is automatically included in the default wrapper.
type RequestBodyExtractor ¶
type RequestBodyExtractor interface {
// Extract extracts the request body into a reflect.Value of the specified type.
Extract(ctx context.Context, reader io.Reader, reqBodyType reflect.Type) (reflect.Value, error)
// ExtractV2 extracts the request body into a pointer directly.
ExtractV2(ctx context.Context, reader io.Reader, ptr any) error
}
RequestBodyExtractor is responsible for extracting and unmarshaling request bodies. It supports both reflection-based and direct pointer-based extraction.
type ResponseBodyMapper ¶
type ResponseBodyMapper interface {
// Map marshals the result and writes it to the http.ResponseWriter.
Map(ctx context.Context, result any, w http.ResponseWriter) error
}
ResponseBodyMapper is responsible for marshaling and writing response bodies.
type Validator ¶
type Validator interface {
// Validate returns true if valid and a map of field names to error messages.
Validate(value any) (bool, map[string]string)
}
Validator validates a value and returns whether it's valid along with field-level error details.
type Wrappable ¶ added in v1.61.0
type Wrappable interface {
Wrap(wrapper Wrapper) http2.HandlerFunc
}
Wrappable is an interface for types that can be wrapped into an http.HandlerFunc. Implementations should handle request extraction and response mapping.
type Wrapper ¶
type Wrapper struct {
ParamMappers map[string]ParamMapper
BodyExtractor RequestBodyExtractor
BodyMapper ResponseBodyMapper
Middlewares []http2.Middleware
Logger log.Logger
}
Wrapper is the core component for building HTTP endpoints. It combines parameter mapping, body extraction, response mapping, and middleware support.
func DefaultWrapper ¶
func DefaultWrapper(logger log.Logger, logMiddleware LogMiddleware, restMiddlewares ...http.Middleware) Wrapper
DefaultWrapper creates a pre-configured Wrapper with common middleware and settings. It includes request logging, metrics collection, tracing, error handling, and recovery. The default maximum request body size is 64MB.
func NewWrapper ¶
func NewWrapper( paramMappers []ParamMapper, bodyExtractor RequestBodyExtractor, bodyMapper ResponseBodyMapper, logger log.Logger, ) Wrapper
NewWrapper creates a new Wrapper with the specified configuration. Parameter mappers are stored in a map for efficient type lookup.
func (Wrapper) Endpoint ¶
func (m Wrapper) Endpoint(f any) http.HandlerFunc
Endpoint wraps a function as an http.HandlerFunc.
Use EndpointV2 with New, NewWithoutResponse, NewWithRequest, or NewDefaultHttp instead. EndpointV2 avoids reflection overhead by using the Wrappable interface.
func (Wrapper) EndpointV2 ¶ added in v1.61.0
func (m Wrapper) EndpointV2(w Wrappable) http.HandlerFunc
EndpointV2 wraps a Wrappable implementation as an http.HandlerFunc. It applies middleware in reverse order (last middleware executes first). This version avoids reflection overhead and is preferred for production use.
func (Wrapper) WithMiddlewares ¶
func (m Wrapper) WithMiddlewares(middlewares ...http2.Middleware) Wrapper
WithMiddlewares returns a new Wrapper with additional middleware appended. The original Wrapper remains unchanged (immutable).
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package buffer provides a ResponseWriter wrapper that buffers request and response bodies.
|
Package buffer provides a ResponseWriter wrapper that buffers request and response bodies. |
|
Package httplog provides HTTP request/response logging middleware.
|
Package httplog provides HTTP request/response logging middleware. |