Documentation
¶
Overview ¶
Package server provides enhanced HTTP handler functionality with type-safe request/response handling.
Package server provides enhanced HTTP handler functionality with type-safe request/response handling.
Package server provides HTTP server functionality using Echo framework. It includes middleware setup, routing, and request handling.
Package server provides request validation functionality. It wraps go-playground/validator with custom validation logic and error formatting.
Index ¶
- Constants
- Variables
- func CORS() echo.MiddlewareFunc
- func DELETE[T any, R any](hr *HandlerRegistry, r RouteRegistrar, path string, handler HandlerFunc[T, R], ...)
- func GET[T any, R any](hr *HandlerRegistry, r RouteRegistrar, path string, handler HandlerFunc[T, R], ...)
- func HEAD[T any, R any](hr *HandlerRegistry, r RouteRegistrar, path string, handler HandlerFunc[T, R], ...)
- func Logger(log logger.Logger) echo.MiddlewareFunc
- func OPTIONS[T any, R any](hr *HandlerRegistry, r RouteRegistrar, path string, handler HandlerFunc[T, R], ...)
- func PATCH[T any, R any](hr *HandlerRegistry, r RouteRegistrar, path string, handler HandlerFunc[T, R], ...)
- func POST[T any, R any](hr *HandlerRegistry, r RouteRegistrar, path string, handler HandlerFunc[T, R], ...)
- func PUT[T any, R any](hr *HandlerRegistry, r RouteRegistrar, path string, handler HandlerFunc[T, R], ...)
- func PerformanceStats() echo.MiddlewareFunc
- func RateLimit(requestsPerSecond int) echo.MiddlewareFunc
- func RegisterHandler[T any, R any](hr *HandlerRegistry, r RouteRegistrar, method, path string, ...)
- func SetupMiddlewares(e *echo.Echo, log logger.Logger, cfg *config.Config)
- func Timing() echo.MiddlewareFunc
- func TraceContext() echo.MiddlewareFunc
- func WrapHandler[T any, R any](handlerFunc HandlerFunc[T, R], binder *RequestBinder, cfg *config.Config) echo.HandlerFunc
- type APIErrorResponse
- type APIResponse
- type BadRequestError
- type BaseAPIError
- type BusinessLogicError
- type ConflictError
- type FieldError
- type ForbiddenError
- type HandlerContext
- type HandlerFunc
- type HandlerRegistry
- type IAPIError
- type InternalServerError
- type NoContentResult
- type NotFoundError
- type RequestBinder
- type Result
- type ResultLike
- type RouteDescriptor
- type RouteOption
- type RouteRegistrar
- type RouteRegistry
- func (r *RouteRegistry) AddRoute(descriptor *RouteDescriptor)
- func (r *RouteRegistry) Clear()
- func (r *RouteRegistry) Count() int
- func (r *RouteRegistry) GetByModule(moduleName string) []RouteDescriptor
- func (r *RouteRegistry) GetByPath(path string) []RouteDescriptor
- func (r *RouteRegistry) GetRoutes() []RouteDescriptor
- func (r *RouteRegistry) GetRoutesByMethod(method string) []RouteDescriptor
- func (r *RouteRegistry) GetRoutesByModule(moduleName string) []RouteDescriptor
- func (r *RouteRegistry) Register(descriptor *RouteDescriptor)
- type Server
- type ServiceUnavailableError
- type TooManyRequestsError
- type UnauthorizedError
- type ValidationError
- type Validator
Constants ¶
const ( BurstMultiplier = 2 RateLimitCleanup = time.Minute * 3 )
Variables ¶
var DefaultRouteRegistry = &RouteRegistry{}
Global registry instance (package level)
Functions ¶
func CORS ¶
func CORS() echo.MiddlewareFunc
CORS returns a CORS middleware configured for the application. It allows cross-origin requests with appropriate security headers.
func DELETE ¶ added in v0.3.0
func DELETE[T any, R any](hr *HandlerRegistry, r RouteRegistrar, path string, handler HandlerFunc[T, R], opts ...RouteOption)
DELETE registers a DELETE handler with optional route configuration.
func GET ¶ added in v0.3.0
func GET[T any, R any](hr *HandlerRegistry, r RouteRegistrar, path string, handler HandlerFunc[T, R], opts ...RouteOption)
GET registers a GET handler with optional route configuration.
func HEAD ¶ added in v0.5.0
func HEAD[T any, R any](hr *HandlerRegistry, r RouteRegistrar, path string, handler HandlerFunc[T, R], opts ...RouteOption)
HEAD registers a HEAD handler with optional route configuration.
func Logger ¶
func Logger(log logger.Logger) echo.MiddlewareFunc
Logger returns a request logging middleware using structured logging. It logs HTTP requests with method, URI, status, latency, and request ID.
func OPTIONS ¶ added in v0.5.0
func OPTIONS[T any, R any](hr *HandlerRegistry, r RouteRegistrar, path string, handler HandlerFunc[T, R], opts ...RouteOption)
OPTIONS registers an OPTIONS handler with optional route configuration.
func PATCH ¶ added in v0.3.0
func PATCH[T any, R any](hr *HandlerRegistry, r RouteRegistrar, path string, handler HandlerFunc[T, R], opts ...RouteOption)
PATCH registers a PATCH handler with optional route configuration.
func POST ¶ added in v0.3.0
func POST[T any, R any](hr *HandlerRegistry, r RouteRegistrar, path string, handler HandlerFunc[T, R], opts ...RouteOption)
POST registers a POST handler with optional route configuration.
func PUT ¶ added in v0.3.0
func PUT[T any, R any](hr *HandlerRegistry, r RouteRegistrar, path string, handler HandlerFunc[T, R], opts ...RouteOption)
PUT registers a PUT handler with optional route configuration.
func PerformanceStats ¶
func PerformanceStats() echo.MiddlewareFunc
PerformanceStats returns middleware that initializes operation tracking for each request. It adds both AMQP message counter and database operation counter to the request context that can be incremented by messaging clients and database layer, then logged in the request logger.
func RateLimit ¶
func RateLimit(requestsPerSecond int) echo.MiddlewareFunc
RateLimit returns a rate limiting middleware with the specified requests per second. It limits the number of requests from each IP address to prevent abuse. If requestsPerSecond is 0 or negative, rate limiting is disabled.
func RegisterHandler ¶ added in v0.3.0
func RegisterHandler[T any, R any]( hr *HandlerRegistry, r RouteRegistrar, method, path string, handler HandlerFunc[T, R], opts ...RouteOption, )
RegisterHandler registers a typed handler with the route registrar and captures metadata.
func SetupMiddlewares ¶
SetupMiddlewares configures and registers all HTTP middlewares for the Echo server. It sets up CORS, logging, recovery, security headers, rate limiting, and other essential middleware.
func Timing ¶
func Timing() echo.MiddlewareFunc
Timing returns a middleware that adds response time headers to HTTP responses. It measures request processing time and adds an X-Response-Time header.
func TraceContext ¶ added in v0.3.0
func TraceContext() echo.MiddlewareFunc
TraceContext injects the resolved trace ID and W3C trace context headers from the Echo request/response into the request context, so that outbound HTTP clients can propagate them without depending on Echo.
func WrapHandler ¶ added in v0.3.0
func WrapHandler[T any, R any]( handlerFunc HandlerFunc[T, R], binder *RequestBinder, cfg *config.Config, ) echo.HandlerFunc
WrapHandler wraps a business logic handler into an Echo-compatible handler. It handles request binding, validation, response formatting, and error handling.
Types ¶
type APIErrorResponse ¶ added in v0.3.0
type APIErrorResponse struct {
Code string `json:"code"`
Message string `json:"message"`
Details map[string]any `json:"details,omitempty"`
}
APIErrorResponse represents the error portion of an API response.
type APIResponse ¶ added in v0.3.0
type APIResponse struct {
Data any `json:"data,omitempty"`
Error *APIErrorResponse `json:"error,omitempty"`
Meta map[string]any `json:"meta"`
}
APIResponse represents the standardized API response format.
type BadRequestError ¶ added in v0.3.0
type BadRequestError struct {
*BaseAPIError
}
BadRequestError represents bad request errors.
func NewBadRequestError ¶ added in v0.3.0
func NewBadRequestError(message string) *BadRequestError
NewBadRequestError creates a new bad request error.
type BaseAPIError ¶ added in v0.3.0
type BaseAPIError struct {
// contains filtered or unexported fields
}
BaseAPIError provides a basic implementation of IAPIError.
func NewBaseAPIError ¶ added in v0.3.0
func NewBaseAPIError(code, message string, httpStatus int) *BaseAPIError
NewBaseAPIError creates a new base API error.
func (*BaseAPIError) Details ¶ added in v0.3.0
func (e *BaseAPIError) Details() map[string]any
Details returns additional error details.
func (*BaseAPIError) Error ¶ added in v0.3.0
func (e *BaseAPIError) Error() string
Error implements the error interface for BaseAPIError. It returns a concise representation suitable for logs and debugging.
func (*BaseAPIError) ErrorCode ¶ added in v0.3.0
func (e *BaseAPIError) ErrorCode() string
ErrorCode returns the error code.
func (*BaseAPIError) HTTPStatus ¶ added in v0.3.0
func (e *BaseAPIError) HTTPStatus() int
HTTPStatus returns the HTTP status code.
func (*BaseAPIError) Message ¶ added in v0.3.0
func (e *BaseAPIError) Message() string
Message returns the error message.
func (*BaseAPIError) WithDetails ¶ added in v0.3.0
func (e *BaseAPIError) WithDetails(key string, value any) *BaseAPIError
WithDetails adds details to the error.
type BusinessLogicError ¶ added in v0.3.0
type BusinessLogicError struct {
*BaseAPIError
}
BusinessLogicError represents domain-specific business logic errors.
func NewBusinessLogicError ¶ added in v0.3.0
func NewBusinessLogicError(code, message string) *BusinessLogicError
NewBusinessLogicError creates a new business logic error.
type ConflictError ¶ added in v0.3.0
type ConflictError struct {
*BaseAPIError
}
ConflictError represents resource conflict errors.
func NewConflictError ¶ added in v0.3.0
func NewConflictError(message string) *ConflictError
NewConflictError creates a new conflict error.
type FieldError ¶
type FieldError struct {
Field string `json:"field"`
Message string `json:"message"`
Value string `json:"value,omitempty"`
}
FieldError represents a validation error for a specific field. It includes the field name, error message, and the invalid value.
type ForbiddenError ¶ added in v0.3.0
type ForbiddenError struct {
*BaseAPIError
}
ForbiddenError represents authorization errors.
func NewForbiddenError ¶ added in v0.3.0
func NewForbiddenError(message string) *ForbiddenError
NewForbiddenError creates a new forbidden error.
type HandlerContext ¶ added in v0.3.0
HandlerContext provides access to Echo context and additional utilities when needed.
type HandlerFunc ¶ added in v0.3.0
type HandlerFunc[T any, R any] func(request T, ctx HandlerContext) (R, IAPIError)
HandlerFunc defines the new handler signature that focuses on business logic.
type HandlerRegistry ¶ added in v0.3.0
type HandlerRegistry struct {
// contains filtered or unexported fields
}
HandlerRegistry manages enhanced handlers and provides registration utilities.
func NewHandlerRegistry ¶ added in v0.3.0
func NewHandlerRegistry(cfg *config.Config) *HandlerRegistry
NewHandlerRegistry creates a new handler registry with the given validator and config.
type IAPIError ¶ added in v0.3.0
type IAPIError interface {
ErrorCode() string
Message() string
HTTPStatus() int
Details() map[string]any
}
IAPIError defines the interface for API errors with structured information.
type InternalServerError ¶ added in v0.3.0
type InternalServerError struct {
*BaseAPIError
}
InternalServerError represents internal server errors.
func NewInternalServerError ¶ added in v0.3.0
func NewInternalServerError(message string) *InternalServerError
NewInternalServerError creates a new internal server error.
type NoContentResult ¶ added in v0.3.0
type NoContentResult struct{}
NoContentResult represents a 204 No Content response without a body
func NoContent ¶ added in v0.3.0
func NoContent() NoContentResult
NoContent returns a 204 No Content result without a response body
func (NoContentResult) ResultMeta ¶ added in v0.3.0
func (NoContentResult) ResultMeta() (status int, headers http.Header, data any)
ResultMeta implements ResultLike for NoContentResult
type NotFoundError ¶ added in v0.3.0
type NotFoundError struct {
*BaseAPIError
}
NotFoundError represents resource not found errors.
func NewNotFoundError ¶ added in v0.3.0
func NewNotFoundError(resource string) *NotFoundError
NewNotFoundError creates a new not found error.
type RequestBinder ¶ added in v0.3.0
type RequestBinder struct{}
RequestBinder handles binding request data to structs with validation.
func NewRequestBinder ¶ added in v0.3.0
func NewRequestBinder() *RequestBinder
NewRequestBinder creates a new request binder with the given validator.
type Result ¶ added in v0.3.0
Result is a generic success wrapper allowing handlers to customize status and headers while preserving type safety of the response payload.
type ResultLike ¶ added in v0.3.0
ResultLike exposes status, headers, and payload for successful responses.
type RouteDescriptor ¶ added in v0.5.0
type RouteDescriptor struct {
Method string // HTTP method (GET, POST, etc.)
Path string // Route path pattern (/users/:id)
HandlerID string // Unique identifier for handler function
HandlerName string // Function name (e.g., "getUser")
ModuleName string // Module that registered this route
Package string // Go package path
RequestType reflect.Type // Request type T from HandlerFunc[T, R]
ResponseType reflect.Type // Response type R from HandlerFunc[T, R]
Middleware []string // Applied middleware names
Tags []string // Optional grouping tags
Summary string // Optional summary from comments
Description string // Optional description from comments
}
RouteDescriptor captures metadata about a registered route
type RouteOption ¶ added in v0.5.0
type RouteOption func(*RouteDescriptor)
RouteOption for configuring route descriptors during registration
func WithDescription ¶ added in v0.5.0
func WithDescription(description string) RouteOption
WithDescription sets a detailed description for the route
func WithHandlerName ¶ added in v0.5.0
func WithHandlerName(name string) RouteOption
WithHandlerName explicitly sets the handler function name
func WithMiddleware ¶ added in v0.5.0
func WithMiddleware(middlewareNames ...string) RouteOption
WithMiddleware records middleware applied to this route
func WithModule ¶ added in v0.5.0
func WithModule(name string) RouteOption
WithModule sets the module name for a route
func WithSummary ¶ added in v0.5.0
func WithSummary(summary string) RouteOption
WithSummary sets a summary description for the route
func WithTags ¶ added in v0.5.0
func WithTags(tags ...string) RouteOption
WithTags adds tags to a route for grouping and organization
type RouteRegistrar ¶ added in v0.5.0
type RouteRegistrar interface {
Add(method, path string, handler echo.HandlerFunc, middleware ...echo.MiddlewareFunc) *echo.Route
Group(prefix string, middleware ...echo.MiddlewareFunc) RouteRegistrar
Use(middleware ...echo.MiddlewareFunc)
FullPath(path string) string
}
RouteRegistrar abstracts the subset of Echo's routing features that modules need while allowing the server to enforce common behavior such as base-path handling. Implementations may wrap Echo groups to ensure routes are consistently registered.
type RouteRegistry ¶ added in v0.5.0
type RouteRegistry struct {
// contains filtered or unexported fields
}
RouteRegistry maintains discovered routes for introspection
func (*RouteRegistry) AddRoute ¶ added in v0.5.0
func (r *RouteRegistry) AddRoute(descriptor *RouteDescriptor)
AddRoute is an alias for Register for consistency with test expectations
func (*RouteRegistry) Clear ¶ added in v0.5.0
func (r *RouteRegistry) Clear()
Clear removes all registered routes (useful for testing)
func (*RouteRegistry) Count ¶ added in v0.5.0
func (r *RouteRegistry) Count() int
Count returns the number of registered routes
func (*RouteRegistry) GetByModule ¶ added in v0.5.0
func (r *RouteRegistry) GetByModule(moduleName string) []RouteDescriptor
GetByModule returns routes for a specific module
func (*RouteRegistry) GetByPath ¶ added in v0.5.0
func (r *RouteRegistry) GetByPath(path string) []RouteDescriptor
GetByPath returns routes for a specific path pattern
func (*RouteRegistry) GetRoutes ¶ added in v0.5.0
func (r *RouteRegistry) GetRoutes() []RouteDescriptor
GetRoutes returns a copy of all registered routes
func (*RouteRegistry) GetRoutesByMethod ¶ added in v0.5.0
func (r *RouteRegistry) GetRoutesByMethod(method string) []RouteDescriptor
GetRoutesByMethod filters routes by HTTP method
func (*RouteRegistry) GetRoutesByModule ¶ added in v0.5.0
func (r *RouteRegistry) GetRoutesByModule(moduleName string) []RouteDescriptor
GetRoutesByModule filters routes by module name (alias for GetByModule)
func (*RouteRegistry) Register ¶ added in v0.5.0
func (r *RouteRegistry) Register(descriptor *RouteDescriptor)
Register adds a route descriptor to the registry
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server represents an HTTP server instance with Echo framework. It manages server lifecycle, configuration, and request handling.
func New ¶
New creates a new HTTP server instance with the given configuration and logger. It initializes Echo with middlewares, error handling, and health check endpoints.
func (*Server) Echo ¶
Echo returns the underlying Echo instance for route registration. This allows modules to register their routes with the server.
func (*Server) ModuleGroup ¶ added in v0.5.0
func (s *Server) ModuleGroup() RouteRegistrar
ModuleGroup returns an Echo group with the base path applied for module route registration. If no base path is configured, it returns a group with empty prefix.
type ServiceUnavailableError ¶ added in v0.3.0
type ServiceUnavailableError struct {
}
ServiceUnavailableError represents service unavailable errors.
func NewServiceUnavailableError ¶ added in v0.3.0
func NewServiceUnavailableError(message string) *ServiceUnavailableError
NewServiceUnavailableError creates a new service unavailable error.
type TooManyRequestsError ¶ added in v0.3.0
type TooManyRequestsError struct {
*BaseAPIError
}
TooManyRequestsError represents rate limiting errors.
func NewTooManyRequestsError ¶ added in v0.3.0
func NewTooManyRequestsError(message string) *TooManyRequestsError
NewTooManyRequestsError creates a new too many requests error.
type UnauthorizedError ¶ added in v0.3.0
type UnauthorizedError struct {
}
UnauthorizedError represents authentication errors.
func NewUnauthorizedError ¶ added in v0.3.0
func NewUnauthorizedError(message string) *UnauthorizedError
NewUnauthorizedError creates a new unauthorized error.
type ValidationError ¶
type ValidationError struct {
Errors []FieldError `json:"errors"`
}
ValidationError wraps validation errors with better messages and structured field errors. It provides a standardized format for validation error responses.
func NewValidationError ¶
func NewValidationError(errs validator.ValidationErrors) *ValidationError
NewValidationError creates a ValidationError from go-playground/validator errors. It converts the errors into a more user-friendly format with descriptive messages.
func (*ValidationError) Error ¶
func (ve *ValidationError) Error() string
type Validator ¶
type Validator struct {
// contains filtered or unexported fields
}
Validator wraps go-playground/validator with custom validation logic. It provides request validation functionality with custom validators.
func NewValidator ¶
func NewValidator() *Validator
NewValidator creates a new Validator instance with custom validation rules registered.
func (*Validator) GetValidator ¶ added in v0.3.0
GetValidator returns the underlying validator instance.