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 EscalateSeverity(c echo.Context, level zerolog.Level)
- 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 IPPreGuard(threshold int) echo.MiddlewareFunc
- func LoggerWithConfig(log logger.Logger, cfg LoggerConfig) 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 TenantMiddleware(resolver multitenant.TenantResolver, skipper SkipperFunc) echo.MiddlewareFunc
- func Timeout(duration time.Duration) echo.MiddlewareFunc
- 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 LoggerConfig
- 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) ByModule(moduleName string) []RouteDescriptor
- func (r *RouteRegistry) ByPath(path string) []RouteDescriptor
- func (r *RouteRegistry) Clear()
- func (r *RouteRegistry) Count() int
- func (r *RouteRegistry) Register(descriptor *RouteDescriptor)
- func (r *RouteRegistry) Routes() []RouteDescriptor
- func (r *RouteRegistry) RoutesByMethod(method string) []RouteDescriptor
- func (r *RouteRegistry) RoutesByModule(moduleName string) []RouteDescriptor
- type Server
- type ServiceUnavailableError
- type SkipperFunc
- type TooManyRequestsError
- type UnauthorizedError
- type ValidationError
- type Validator
Constants ¶
const ( // DefaultReadTimeout is the maximum duration for reading the entire request. // This includes reading the request body and headers. // Used in server.go and server_test.go (28+ occurrences). DefaultReadTimeout = 15 * time.Second // DefaultWriteTimeout is the maximum duration before timing out writes of the response. // This is set from the start of the request handler to the end of the response write. DefaultWriteTimeout = 15 * time.Second // DefaultIdleTimeout is the maximum amount of time to wait for the next request // when keep-alives are enabled. DefaultIdleTimeout = 60 * time.Second // DefaultShutdownTimeout is the maximum time to wait for graceful shutdown. // This allows in-flight requests to complete before forceful termination. DefaultShutdownTimeout = 30 * time.Second // DefaultAPITimeout is the maximum duration for external API calls. // Used in HTTP client configurations for backend service communication. DefaultAPITimeout = 30 * time.Second )
const ( // TestShortTimeout is a very short timeout for testing timeout behavior. // Used in handler tests to verify proper timeout error handling. TestShortTimeout = 100 * time.Millisecond // TestMediumTimeout is a moderate timeout for async operations in tests. TestMediumTimeout = 1 * time.Second // TestLongTimeout is a generous timeout for slow operations in tests. // Used when testing complex handlers or integration scenarios. TestLongTimeout = 5 * time.Second )
const ( // HeaderXResponseTime is used to report request processing duration. // Set by the timing middleware on all responses. HeaderXResponseTime = "X-Response-Time" // HeaderXRealIP contains the client's real IP address when behind a proxy. // Used by rate limiting and IP-based access control. HeaderXRealIP = "X-Real-IP" // HeaderXForwardedFor contains a comma-separated list of IPs from proxies. // The first entry is typically the original client IP. HeaderXForwardedFor = "X-Forwarded-For" // HeaderXForwardedHost contains the original host requested by the client. // Used in multi-tenant routing with proxy support. HeaderXForwardedHost = "X-Forwarded-Host" // HeaderXTenantID identifies the tenant in multi-tenant requests. // Default header name for tenant resolution. HeaderXTenantID = "X-Tenant-ID" )
const ( // HeaderXXSSProtection enables XSS filtering in browsers. // Value "1; mode=block" enables protection and blocks rendering on detection. HeaderXXSSProtection = "X-XSS-Protection" // HeaderXContentTypeOptions prevents MIME type sniffing. // Value "nosniff" instructs browsers to strictly follow declared content types. HeaderXContentTypeOptions = "X-Content-Type-Options" // HeaderXFrameOptions controls page framing for clickjacking protection. // Values: "DENY", "SAMEORIGIN", or "ALLOW-FROM uri". HeaderXFrameOptions = "X-Frame-Options" )
const ( // HeaderAccessControlAllowOrigin specifies allowed origins for CORS requests. // Value "*" allows all origins, or specific origin like "https://example.com". HeaderAccessControlAllowOrigin = "Access-Control-Allow-Origin" // HeaderAccessControlAllowMethods lists allowed HTTP methods for CORS. // Example: "GET, POST, PUT, DELETE, OPTIONS". HeaderAccessControlAllowMethods = "Access-Control-Allow-Methods" // HeaderAccessControlAllowHeaders lists allowed request headers for CORS. // Example: "Content-Type, Authorization, X-Request-ID". HeaderAccessControlAllowHeaders = "Access-Control-Allow-Headers" // HeaderAccessControlAllowCredentials indicates if credentials are allowed. // Value "true" allows cookies and authorization headers in CORS requests. HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials" // HeaderAccessControlExposeHeaders lists headers accessible to client scripts. // Example: "X-Response-Time, X-Request-ID". HeaderAccessControlExposeHeaders = "Access-Control-Expose-Headers" // HeaderAccessControlMaxAge specifies preflight cache duration in seconds. // Example: "86400" (24 hours). HeaderAccessControlMaxAge = "Access-Control-Max-Age" // HeaderAccessControlRequestMethod indicates the method for preflight requests. // Sent by browsers in OPTIONS preflight requests. HeaderAccessControlRequestMethod = "Access-Control-Request-Method" // HeaderAccessControlRequestHeaders indicates headers for preflight requests. // Sent by browsers in OPTIONS preflight requests. HeaderAccessControlRequestHeaders = "Access-Control-Request-Headers" )
const ( BurstMultiplier = 2 RateLimitCleanup = time.Minute * 3 )
const ( // IPPreGuardCleanup defines how long to keep IP buckets in memory after last use IPPreGuardCleanup = time.Minute * 5 )
const RequestLogContextKey = "_request_log_ctx"
RequestLogContextKey is the public key used to store request logging context in Echo's context. This allows external code to access or modify request logging state if needed.
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 EscalateSeverity ¶ added in v0.13.0
EscalateSeverity allows application code to explicitly escalate request severity. Useful for non-logging events that should trigger WARN+ action logs (e.g., rate limiting).
Example:
if rateLimit.Exceeded() {
server.EscalateSeverity(c, zerolog.WarnLevel)
}
Thread-safe: Can be called from multiple goroutines concurrently.
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 IPPreGuard ¶ added in v0.9.0
func IPPreGuard(threshold int) echo.MiddlewareFunc
IPPreGuard returns an IP-based rate limiting middleware for early attack prevention. This middleware runs before tenant resolution to block obvious attacks and invalid tenant sprays. It uses a higher threshold than the main rate limiter and only protects against IP-based attacks. If threshold is 0 or negative, IP pre-guard is disabled.
func LoggerWithConfig ¶ added in v0.13.0
func LoggerWithConfig(log logger.Logger, cfg LoggerConfig) echo.MiddlewareFunc
LoggerWithConfig returns a request logging middleware with custom configuration. It implements dual-mode logging:
- Action logs (log.type="action"): Request summaries for INFO-level requests
- Trace logs (log.type="trace"): Application debug logs (WARN+ only)
The middleware tracks request-scoped severity escalation. If any log during the request lifecycle reaches WARN+, the request is logged as a trace log. Otherwise, a synthesized action log summary is emitted at request completion.
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 ¶
func SetupMiddlewares(e *echo.Echo, log logger.Logger, cfg *config.Config, healthPath, readyPath string)
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. healthPath and readyPath are used by the tenant middleware skipper to bypass probe endpoints.
func TenantMiddleware ¶ added in v0.9.0
func TenantMiddleware(resolver multitenant.TenantResolver, skipper SkipperFunc) echo.MiddlewareFunc
TenantMiddleware resolves the tenant ID and injects it into the request context. If a skipper function is provided, certain routes (e.g., health probes) can bypass tenant resolution. If skipper is nil, all routes will undergo tenant resolution.
func Timeout ¶ added in v0.13.0
func Timeout(duration time.Duration) echo.MiddlewareFunc
Timeout returns middleware that adds a request-scoped deadline without swapping Echo's response writer. When the configured duration elapses the handler will observe context cancellation and higher layers will surface a 503 via the centralized error handler.
Why not use Echo's middleware.TimeoutWithConfig? Echo's timeout wraps net/http.TimeoutHandler which swaps the response writer with a timeoutWriter. When timeouts occur, this invalidates Echo's response object (c.Response() returns nil), causing panics in logging/middleware that access response headers/status. By using context-only timeouts, we maintain response validity while still enforcing deadlines.
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. Supports both value and pointer types for requests (T) and responses (R). Pointer types eliminate copy overhead for large payloads (>1KB recommended).
This function now delegates to handlerWrapper which composes specialized components: - contextChecker: Detects request cancellation/timeout - requestProcessor: Allocates, binds, and validates requests - responseHandler: Formats success and error responses
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.
func (*BadRequestError) Error ¶ added in v0.19.0
func (e *BadRequestError) Error() string
Error implements the error interface.
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.
func (*BusinessLogicError) Error ¶ added in v0.19.0
func (e *BusinessLogicError) Error() string
Error implements the error interface.
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.
func (*ConflictError) Error ¶ added in v0.19.0
func (e *ConflictError) Error() string
Error implements the error interface.
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.
func (FieldError) Error ¶ added in v0.19.0
func (e FieldError) Error() string
Error implements the error interface.
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.
func (*ForbiddenError) Error ¶ added in v0.19.0
func (e *ForbiddenError) Error() string
Error implements the error interface.
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.
func (*InternalServerError) Error ¶ added in v0.19.0
func (e *InternalServerError) Error() string
Error implements the error interface.
type LoggerConfig ¶ added in v0.13.0
type LoggerConfig struct {
// HealthPath specifies the health probe endpoint to exclude from logging
HealthPath string
// ReadyPath specifies the readiness probe endpoint to exclude from logging
ReadyPath string
// SlowRequestThreshold defines the latency threshold for marking requests as slow (WARN severity)
// Requests exceeding this duration are logged with result_code="WARN" even if HTTP status is 2xx
SlowRequestThreshold time.Duration
}
LoggerConfig configures the request logging middleware with dual-mode logging support.
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.
func (*NotFoundError) Error ¶ added in v0.19.0
func (e *NotFoundError) Error() string
Error implements the error interface.
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) ByModule ¶ added in v0.19.0
func (r *RouteRegistry) ByModule(moduleName string) []RouteDescriptor
ByModule returns routes for a specific module
func (*RouteRegistry) ByPath ¶ added in v0.19.0
func (r *RouteRegistry) ByPath(path string) []RouteDescriptor
ByPath returns routes for a specific path pattern
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) Register ¶ added in v0.5.0
func (r *RouteRegistry) Register(descriptor *RouteDescriptor)
Register adds a route descriptor to the registry
func (*RouteRegistry) Routes ¶ added in v0.19.0
func (r *RouteRegistry) Routes() []RouteDescriptor
Routes returns a copy of all registered routes
func (*RouteRegistry) RoutesByMethod ¶ added in v0.19.0
func (r *RouteRegistry) RoutesByMethod(method string) []RouteDescriptor
RoutesByMethod filters routes by HTTP method
func (*RouteRegistry) RoutesByModule ¶ added in v0.19.0
func (r *RouteRegistry) RoutesByModule(moduleName string) []RouteDescriptor
RoutesByModule filters routes by module name (alias for ByModule)
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.
func (*Server) RegisterReadyHandler ¶ added in v0.9.0
func (s *Server) RegisterReadyHandler(handler echo.HandlerFunc)
RegisterReadyHandler overrides the ready endpoint handler. Passing nil restores the default handler.
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.
func (*ServiceUnavailableError) Error ¶ added in v0.19.0
func (e *ServiceUnavailableError) Error() string
Error implements the error interface.
type SkipperFunc ¶ added in v0.9.0
SkipperFunc defines a function to skip middleware processing for certain requests.
func CreateProbeSkipper ¶ added in v0.9.0
func CreateProbeSkipper(healthPath, readyPath string) SkipperFunc
CreateProbeSkipper creates a skipper function for health probe endpoints. It returns true for paths that should bypass tenant middleware (health, ready). The implementation uses exact path matching for optimal performance and precision.
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.
func (*TooManyRequestsError) Error ¶ added in v0.19.0
func (e *TooManyRequestsError) Error() string
Error implements the error interface.
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.
func (*UnauthorizedError) Error ¶ added in v0.19.0
func (e *UnauthorizedError) Error() string
Error implements the error interface.
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.