Documentation
¶
Overview ¶
Package httputil provides HTTP utility functions for building robust web APIs in Go. It implements patterns for type-safe request/response handling with validation, structured error reporting, and OpenAPI documentation generation.
Key features: - DTO (Data Transfer Object) pattern for request/response marshaling - Declarative validation using struct schemas - Option pattern configuration for request processing - Automatic error classification and JSON error responses - Context-aware request handling - Integrated OpenAPI/Swagger documentation generation - TUS protocol support for file uploads - Route registration with built-in middleware support
The package emphasizes: - Type safety through generics - Clear separation of concerns - Customizable error handling - Consistent JSON formatting - Middleware-ready components - Self-documenting APIs
Router Features: - Unified route registration with access control - Automatic OpenAPI spec generation - Built-in support for common patterns:
- Pagination (_start, _end params)
- Sorting (_sort, _order params)
- Filtering (custom field filters)
- Global search (q param)
- Predefined Swagger definitions for:
- Authenticated endpoints
- Public endpoints
- File uploads (multipart/form-data)
- TUS protocol endpoints
- Paginated responses
Index ¶
- func DecodeAndValidateRequest[M any, D DTORequest[M]](r RequestContext, dto D, opts ...VDOption) (M, bool)
- func EncodeResponse[M any, D DTOResponse[M]](r RequestContext, model M, dto D, opts ...VDOption) error
- func IsValidationError(err error) bool
- func ToJSON[T any](data T) ([]byte, error)
- type DTORequest
- type DTOResponse
- type DTOValidator
- type DefaultErrorHandler
- type ErrorHandler
- type FileUploadResult
- type RequestContext
- func (r RequestContext) Check(msg string, err error) error
- func (r RequestContext) Decode(v any) error
- func (r RequestContext) DecodeForm(key string, v any) error
- func (r RequestContext) Encode(v any) error
- func (r RequestContext) Error(err error, status int) error
- func (r RequestContext) PrepareFileUpload(maxUploadSize int64) (*FileUploadResult, error)
- func (r RequestContext) Validate(validator DTOValidator) error
- func (r RequestContext) ValidateRequest(entity DTOValidator) (map[string]string, error)
- type VDOption
- type ValidationError
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func DecodeAndValidateRequest ¶ added in v0.2.0
func DecodeAndValidateRequest[M any, D DTORequest[M]]( r RequestContext, dto D, opts ...VDOption, ) (M, bool)
DecodeAndValidateRequest handles the complete request processing pipeline:
- Decode request body to DTO
- Validate using DTOValidator interface (if implemented)
- Convert to domain model using ToModel()
Returns:
- The parsed domain model and true on success
- Zero value and false on any error, with error handling delegated to the ErrorHandler
The function uses generics to ensure type safety and accepts optional VDOptions to customize processing behavior per invocation.
func EncodeResponse ¶ added in v0.2.0
func EncodeResponse[M any, D DTOResponse[M]](r RequestContext, model M, dto D, opts ...VDOption) error
EncodeResponse handles the response generation pipeline. It uses generics to ensure type safety when encoding the response.
func IsValidationError ¶ added in v0.2.0
IsValidationError checks if an error is or contains a ValidationError
Types ¶
type DTORequest ¶ added in v0.1.1
DTORequest defines the interface for request Data Transfer Objects that convert HTTP requests to domain models. Implementations should: - Handle validation through the DTOValidator interface (optional) - Convert the raw request to a domain model - Return clean domain objects or validation errors
type DTOResponse ¶ added in v0.1.1
DTOResponse defines the interface for response Data Transfer Objects that convert domain models to HTTP responses. Implementations should: - Format domain objects for JSON serialization - Maintain stable API contracts - Handle serialization-specific logic
type DTOValidator ¶ added in v0.1.1
type DTOValidator interface {
Schema() *z.StructSchema
}
DTOValidator defines the validation interface for Data Transfer Objects. Implementations should return a zog schema that will be applied to validate incoming requests. The schema is used to: - Validate request structure - Provide meaningful error messages - Ensure data integrity before processing
type DefaultErrorHandler ¶ added in v0.3.0
type DefaultErrorHandler struct{}
DefaultErrorHandler provides standardized error handling with: - 400 Bad Request for JSON syntax/type errors - 422 Unprocessable Entity for validation errors - 500 Internal Server Error for all other cases
func (*DefaultErrorHandler) HandleError ¶ added in v0.3.0
func (h *DefaultErrorHandler) HandleError(ctx RequestContext, err error)
HandleError implements ErrorHandler with status code detection
type ErrorHandler ¶ added in v0.3.0
type ErrorHandler interface {
HandleError(ctx RequestContext, err error)
}
ErrorHandler defines the strategy pattern for error handling during request processing. Implementations can customize error logging, formatting, and status code selection.
type FileUploadResult ¶ added in v0.5.2
type FileUploadResult struct {
File io.ReadSeekCloser
Size uint64
Filename string
}
FileUploadResult contains the uploaded file and its metadata
type RequestContext ¶
RequestContext carries HTTP request-scoped values and provides utility methods for handling the complete request/response lifecycle. It combines: - Validation and encoding utilities - Embedded Echo Context for framework features
func Context ¶
func Context(c echo.Context) RequestContext
Context creates a new RequestContext from an Echo context. This should be the primary way to initialize the request context for handlers.
func (RequestContext) Check ¶
func (r RequestContext) Check(msg string, err error) error
Check simplifies error handling by: - Returning nil if err is nil - Wrapping the error with a message - Sending an HTTP 500 response if error exists
func (RequestContext) Decode ¶
func (r RequestContext) Decode(v any) error
Decode reads and parses the request body as JSON into the provided value. Returns an error wrapped with type information if decoding fails
func (RequestContext) DecodeForm ¶
func (r RequestContext) DecodeForm(key string, v any) error
DecodeForm parses and converts form values to various types. Supports: - Standard types (string, int, bool, time.Time) - Slice types from comma-separated values - Custom types implementing UnmarshalText or LoadString interfaces Panics if passed an unsupported type
func (RequestContext) Encode ¶
func (r RequestContext) Encode(v any) error
Encode writes a JSON response to the client with consistent formatting: - Empty slices/maps render as []/{} instead of null - Uses indented JSON for human readability
func (RequestContext) Error ¶
func (r RequestContext) Error(err error, status int) error
Error writes an HTTP error response and returns the error. Formats: - ValidationErrors as 422 Unprocessable Entity with field-specific errors - All other errors using Echo's error handler
func (RequestContext) PrepareFileUpload ¶ added in v0.5.2
func (r RequestContext) PrepareFileUpload(maxUploadSize int64) (*FileUploadResult, error)
PrepareFileUpload handles both multipart form uploads and raw body uploads. It supports: - Multipart form file uploads (with Content-Type: multipart/form-data) - Raw binary uploads (with any other Content-Type) - Automatic handling of seekable vs non-seekable sources - Size validation against maxUploadSize
func (RequestContext) Validate ¶ added in v0.1.1
func (r RequestContext) Validate(validator DTOValidator) error
Validate applies schema validation against a pre-populated DTOValidator. Returns: - nil on successful validation - ValidationError with field-specific errors on failure - Error wrapping original parse failure if schema validation cannot be performed
func (RequestContext) ValidateRequest ¶ added in v0.1.1
func (r RequestContext) ValidateRequest(entity DTOValidator) (map[string]string, error)
ValidateRequest performs validation and returns errors as a map of field->message. This is useful when you need to present validation errors in a structured format. Returns: - (nil, nil) if validation passes - (map, nil) with validation errors if validation fails - (nil, error) if there was a processing error
type VDOption ¶ added in v0.3.0
type VDOption func(*vdConfig)
VDOption configures DecodeAndValidateRequest processing behavior using the option pattern. These allow customizing validation handling per API endpoint while maintaining a consistent interface.
func WithErrorHandler ¶ added in v0.3.0
func WithErrorHandler(h ErrorHandler) VDOption
WithErrorHandler specifies a custom error handler for request processing. This option allows overriding the default error response strategy while maintaining the standard validation and decoding pipeline.
type ValidationError ¶ added in v0.2.0
type ValidationError struct {
FieldErrors map[string]string // Field path -> error message
// contains filtered or unexported fields
}
ValidationError represents structured validation failures with: - Field-specific error messages - Machine-readable error codes - Nested error support through error wrapping
func (*ValidationError) Error ¶ added in v0.2.0
func (v *ValidationError) Error() string
func (*ValidationError) Fields ¶ added in v0.2.0
func (v *ValidationError) Fields() map[string]string
Fields returns the field-specific error messages
func (*ValidationError) Unwrap ¶ added in v0.2.0
func (v *ValidationError) Unwrap() []error