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 ClientIP(r *http.Request, trustedProxies []*net.IPNet) string
- 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 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 ParseCIDRs(cidrs []string) (nets []*net.IPNet, invalid []string)
- func RegisterHandler[T any, R any](hr *HandlerRegistry, r RouteRegistrar, method, path string, ...)
- func SetCaptureStackTraces(enabled bool)
- func SetupMiddlewares(e *echo.Echo, log logger.Logger, cfg *config.Config, observabilityEnabled bool, ...)
- 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
- func (e *BaseAPIError) Details() map[string]any
- func (e *BaseAPIError) Error() string
- func (e *BaseAPIError) ErrorCode() string
- func (e *BaseAPIError) HTTPStatus() int
- func (e *BaseAPIError) Message() string
- func (e *BaseAPIError) StackTrace() []string
- func (e *BaseAPIError) WithDetails(key string, value any) *BaseAPIError
- type BusinessLogicError
- type ConflictError
- type FieldError
- type ForbiddenError
- type Handler
- type HandlerContext
- func (c HandlerContext) EscalateSeverity(level zerolog.Level)
- func (c HandlerContext) Get(key string) any
- func (c HandlerContext) JSON(code int, v any) error
- func (c HandlerContext) Param(name string) string
- func (c HandlerContext) PathParams() []PathParam
- func (c HandlerContext) Query(name string) string
- func (c HandlerContext) Request() *http.Request
- func (c HandlerContext) RequestContext() context.Context
- func (c HandlerContext) RequestHeader(name string) string
- func (c HandlerContext) ResponseWriter() http.ResponseWriter
- func (c HandlerContext) RouteTemplate() string
- func (c HandlerContext) Set(key string, val any)
- func (c HandlerContext) SetPathParams(params []PathParam)
- func (c HandlerContext) SetRequest(r *http.Request)
- func (c HandlerContext) SetRequestContext(ctx context.Context)
- func (c HandlerContext) String(code int, s string) error
- type HandlerFunc
- type HandlerRegistry
- type HandlerRegistryOption
- func WithJOSELogger(log logger.Logger) HandlerRegistryOption
- func WithJOSEMeterProvider(mp metric.MeterProvider) HandlerRegistryOption
- func WithJOSEResolver(r jose.KeyResolver) HandlerRegistryOption
- func WithJOSETracer(t trace.Tracer) HandlerRegistryOption
- func WithLogger(log logger.Logger) HandlerRegistryOption
- type IAPIError
- type InternalServerError
- type LoggerConfig
- type MiddlewareFunc
- func CORS(exposeResponseTime bool, envOverride ...string) MiddlewareFunc
- func IPPreGuard(threshold int) MiddlewareFunc
- func LoggerWithConfig(log logger.Logger, cfg LoggerConfig) MiddlewareFunc
- func PerformanceStats() MiddlewareFunc
- func RateLimit(requestsPerSecond int) MiddlewareFunc
- func RequestEnrich() MiddlewareFunc
- func RequestIDMiddleware() MiddlewareFunc
- func TenantMiddleware(resolver multitenant.TenantResolver, skipper SkipperFunc) MiddlewareFunc
- func Timeout(duration time.Duration) MiddlewareFunc
- func Timing() MiddlewareFunc
- func TraceContext() MiddlewareFunc
- type NoContentResult
- type NotFoundError
- type PathParam
- type RequestBinder
- type Result
- type ResultEnvelopeProvider
- type ResultMetaProvider
- type ResultWithMeta
- type RouteDescriptor
- type RouteOption
- func WithDescription(description string) RouteOption
- func WithHandlerName(name string) RouteOption
- func WithMiddleware(middlewareNames ...string) RouteOption
- func WithModule(name string) RouteOption
- func WithRawResponse() RouteOption
- func WithSummary(summary string) RouteOption
- func WithTags(tags ...string) 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 StackTracer
- type TestContextOption
- 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. 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 = 30 * 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 = 10 * time.Second // DefaultAPITimeout is the maximum duration for external API calls. 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 optional timing middleware only when server.responsetime.enabled // is true (off by default); see ADR-026. 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 ClientIP ¶ added in v0.42.0
ClientIP returns the real client IP for r, with trusted-proxy-chain verification that prevents X-Forwarded-For / X-Real-IP header spoofing. Unlike echo's LegacyIPExtractor (which trusts the left-most XFF entry unconditionally), proxy headers are honored ONLY when the immediate peer (RemoteAddr) is within trustedProxies. This is the secure extraction that access-control decisions (debug allowlist) and rate limiting must use.
Algorithm (RFC 7239):
- Extract the immediate peer IP from RemoteAddr.
- If no trusted proxies are configured, OR the peer is not trusted, return the peer IP and ignore all forwarding headers (an attacker connecting directly cannot forge it).
- If the peer is trusted, walk X-Forwarded-For right-to-left and return the first untrusted IP (the real client). Fall back to X-Real-IP, then the peer IP.
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 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 ParseCIDRs ¶ added in v0.42.0
ParseCIDRs parses a list of CIDR strings into *net.IPNet values, trimming surrounding whitespace on each entry. Entries that fail to parse are returned separately in `invalid` so callers can surface a WARN instead of silently degrading (a dropped trusted-proxy range silently weakens spoofing protection). A nil/empty input yields nil, nil.
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 SetCaptureStackTraces ¶ added in v0.30.0
func SetCaptureStackTraces(enabled bool)
SetCaptureStackTraces toggles stack-trace capture for all subsequently created errors. Intended for the framework bootstrap (server.New) and tests. Safe for concurrent use.
func SetupMiddlewares ¶
func SetupMiddlewares(e *echo.Echo, log logger.Logger, cfg *config.Config, observabilityEnabled bool, 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. observabilityEnabled gates the OTel HTTP instrumentation middleware (passed explicitly, like healthPath/readyPath, so the decision is made by the caller from observability.enabled). healthPath and readyPath are used by the tenant middleware skipper to bypass probe endpoints.
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 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) StackTrace ¶ added in v0.30.0
func (e *BaseAPIError) StackTrace() []string
StackTrace resolves the captured program counters into readable "file:line funcName" strings. Returns nil when no stack was captured — either because SetCaptureStackTraces was off at construction time, or because the error was built without NewBaseAPIError.
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 Handler ¶ added in v0.45.0
type Handler func(c HandlerContext) error
Handler is the untyped, echo-free handler signature for raw routes, the readiness probe, and debug/system endpoints. It writes its own response (via c.JSON / c.String) and is the low-level counterpart to the typed HandlerFunc[T, R].
Handler is NOT related to Raw Response Mode (WithRawResponse / RouteDescriptor.RawResponse, which bypasses the APIResponse envelope for Strangler-Fig routes): the two concepts share no machinery. Handler simply means "an echo-free handler the framework adapts to Echo."
type HandlerContext ¶ added in v0.3.0
HandlerContext gives handlers and middleware framework-neutral access to the request, response, and per-request state. Standard-library types (*http.Request, http.ResponseWriter) are the currency at this boundary; the underlying Echo engine is reachable only through the unexported escape hatch, so application code cannot name an echo type.
func NewHandlerContextForTest ¶ added in v0.45.0
func NewHandlerContextForTest(w http.ResponseWriter, r *http.Request, cfg *config.Config) HandlerContext
NewHandlerContextForTest builds a HandlerContext backed by a real Echo context for use in external-package tests (e.g. app/, scheduler/) that exercise Handler / MiddlewareFunc code but cannot name the unexported escape hatch. It keeps the echo dependency confined to package server. Test-support only — not for production wiring. To seed routing state the synthetic context would otherwise leave empty, use NewHandlerContextForTestWithOptions.
func NewHandlerContextForTestWithOptions ¶ added in v0.47.0
func NewHandlerContextForTestWithOptions(w http.ResponseWriter, r *http.Request, cfg *config.Config, opts ...TestContextOption) HandlerContext
NewHandlerContextForTestWithOptions is NewHandlerContextForTest plus TestContextOption values (e.g. WithRouteTemplate) that seed pre-routing state the engine would otherwise populate during matching. It exists as a separate constructor rather than a variadic on NewHandlerContextForTest so the already-released signature stays API-compatible (adding a variadic changes a function's type identity — apidiff classifies it as incompatible). Test-support only — not for production wiring.
func (HandlerContext) EscalateSeverity ¶ added in v0.45.0
func (c HandlerContext) EscalateSeverity(level zerolog.Level)
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() {
ctx.EscalateSeverity(zerolog.WarnLevel)
}
Thread-safe: Can be called from multiple goroutines concurrently.
func (HandlerContext) Get ¶ added in v0.45.0
func (c HandlerContext) Get(key string) any
Get returns a per-request value previously stored with Set (nil if absent).
func (HandlerContext) JSON ¶ added in v0.45.0
func (c HandlerContext) JSON(code int, v any) error
JSON writes v as a JSON response with the given status code. For raw/system handlers; typed handlers return (R, IAPIError) and let the framework encode.
func (HandlerContext) Param ¶ added in v0.45.0
func (c HandlerContext) Param(name string) string
Param returns the path parameter for name (empty string if absent).
func (HandlerContext) PathParams ¶ added in v0.46.0
func (c HandlerContext) PathParams() []PathParam
PathParams returns the matched path parameters in route-template order. The returned slice is a defensive copy: safe to retain past the request; mutating it does not affect Param() or struct-tag binding. Empty when no route matched (pre-route, 404, 405) — parameter state is only meaningful for a matched route.
func (HandlerContext) Query ¶ added in v0.45.0
func (c HandlerContext) Query(name string) string
Query returns the first query-string value for name (empty string if absent).
func (HandlerContext) Request ¶ added in v0.45.0
func (c HandlerContext) Request() *http.Request
Request returns the underlying *http.Request.
func (HandlerContext) RequestContext ¶ added in v0.45.0
func (c HandlerContext) RequestContext() context.Context
RequestContext returns the request's context.Context. Convenience for the dominant pattern (deadline/cancellation, trace and tenant propagation) so callers rarely need Request() directly.
func (HandlerContext) RequestHeader ¶ added in v0.45.0
func (c HandlerContext) RequestHeader(name string) string
RequestHeader returns the first request header value for name (empty string if absent).
func (HandlerContext) ResponseWriter ¶ added in v0.45.0
func (c HandlerContext) ResponseWriter() http.ResponseWriter
ResponseWriter returns the http.ResponseWriter for the current response.
func (HandlerContext) RouteTemplate ¶ added in v0.46.0
func (c HandlerContext) RouteTemplate() string
RouteTemplate returns the registered route path that matched this request, including any group/base-path prefix (e.g. "/api/cards/:cardId/status"). It is the template the application registered, NOT the concrete URL (use Request().URL.Path for that). Empty before routing completes and on unmatched (404) requests; on 405 the engine sets the best-matching route's template (engine-defined, not a contract).
func (HandlerContext) Set ¶ added in v0.45.0
func (c HandlerContext) Set(key string, val any)
Set stores a per-request value retrievable with Get. Note: this is the request-scoped store, NOT the request's context.Context — to propagate values to downstream handlers and tenant-aware resources (deps.DB(ctx) etc.), use SetRequestContext.
func (HandlerContext) SetPathParams ¶ added in v0.46.0
func (c HandlerContext) SetPathParams(params []PathParam)
SetPathParams replaces the request's path parameters. Subsequent Param(name) calls and param:"name" struct-tag binding observe the new set. The input slice is copied; nil clears all parameters. Injected params are application-supplied — treat them with the same trust as their source value.
func (HandlerContext) SetRequest ¶ added in v0.45.0
func (c HandlerContext) SetRequest(r *http.Request)
SetRequest replaces the underlying *http.Request (e.g. to attach a derived context).
func (HandlerContext) SetRequestContext ¶ added in v0.45.0
func (c HandlerContext) SetRequestContext(ctx context.Context)
SetRequestContext replaces the request's context.Context, the canonical way for middleware to inject values (tenant ID, authenticated principal) that downstream handlers and context-aware resources observe. Equivalent to SetRequest(Request().WithContext(ctx)).
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, opts ...HandlerRegistryOption) *HandlerRegistry
NewHandlerRegistry creates a new handler registry with the given validator and config. Optional HandlerRegistryOption values (e.g., WithJOSEResolver) configure additional behaviors. Existing callers passing only cfg are unaffected.
type HandlerRegistryOption ¶ added in v0.30.0
type HandlerRegistryOption func(*HandlerRegistry)
HandlerRegistryOption configures a HandlerRegistry at construction time. Existing call sites that don't need JOSE pass no options and behave unchanged.
func WithJOSELogger ¶ added in v0.30.0
func WithJOSELogger(log logger.Logger) HandlerRegistryOption
WithJOSELogger attaches a logger used to emit structured ERROR records on JOSE failure paths (decrypt failed, signature invalid, etc.). Records include code, direction, route, and method — never plaintext payloads or key material. When no logger is supplied, JOSE failures still flow through the IAPIError envelope to the wire and to the framework's request logger; this option only adds the dedicated audit-grade record.
func WithJOSEMeterProvider ¶ added in v0.30.0
func WithJOSEMeterProvider(mp metric.MeterProvider) HandlerRegistryOption
WithJOSEMeterProvider attaches an OTEL meter provider used to register the JOSE failure counter and operation-duration histogram. A no-op provider is used by default so instrument creation cannot fail when observability is disabled.
func WithJOSEResolver ¶ added in v0.30.0
func WithJOSEResolver(r jose.KeyResolver) HandlerRegistryOption
WithJOSEResolver enables JOSE protection for routes whose request/response types carry jose: tags. When the resolver is nil or this option is not supplied, JOSE scanning is skipped at registration — but if any route attempts to declare a jose tag, registration will panic with a clear error directing the operator to wire a keystore module.
func WithJOSETracer ¶ added in v0.30.0
func WithJOSETracer(t trace.Tracer) HandlerRegistryOption
WithJOSETracer attaches an OpenTelemetry tracer used to emit spans around JOSE crypto operations (jose.decode_request, jose.encode_response). When no tracer is supplied, a no-op tracer is used so call sites stay branch-free.
func WithLogger ¶ added in v0.36.0
func WithLogger(log logger.Logger) HandlerRegistryOption
WithLogger attaches a general-purpose logger to the handler registry. Used by the response pipeline to emit:
- A structured WARN when a handler-supplied envelope meta key collides with a framework-reserved key (timestamp, traceId).
- A structured DEBUG when raw-response mode drops envelope meta returned by a ResultEnvelopeProvider (typically misconfigured routes).
Independent of WithJOSELogger. Passing nil is a no-op — reserved keys are still dropped, the warning is just suppressed.
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 MiddlewareFunc ¶ added in v0.45.0
type MiddlewareFunc func(c HandlerContext, next func() error) error
MiddlewareFunc is the framework-neutral middleware signature. A middleware runs its own logic, then calls next() to invoke the rest of the chain — or returns an IAPIError WITHOUT calling next to abort the request (the returned error flows through the standard error handler, producing the usual envelope). It is a flat baton-pass rather than Echo's nested func(next) next form; the framework adapts it to Echo internally, so application code never names an echo type.
func CORS ¶
func CORS(exposeResponseTime bool, envOverride ...string) MiddlewareFunc
CORS returns a CORS middleware configured for the application.
Origin policy (fail-closed by default per ADR-022 alias semantics):
- CORS_ORIGINS set: strict allowlist mode, regardless of env.
- CORS_ORIGINS unset AND env is a development alias (development/dev/local): permissive wildcard for dev convenience.
- Otherwise (production, staging, custom envs like production-eu): fail closed — no Access-Control-Allow-Origin header is emitted, so browsers reject cross-origin requests. A WARN is logged at startup.
The env can be passed explicitly via the variadic envOverride argument (preferred — SetupMiddlewares passes cfg.App.Env, which honors the Koanf default of EnvDevelopment when APP_ENV is unset). When omitted, CORS falls back to os.Getenv("APP_ENV") — preserving call sites that existed before the parameter was added.
exposeResponseTime advertises X-Response-Time in Access-Control-Expose-Headers only when the Timing middleware actually emits the header (server.responsetime. enabled). Advertising an expose-header the server never sends is harmless but misleading, so this keeps the CORS contract aligned with what is on the wire.
The returned MiddlewareFunc is the framework-neutral (echo-free) form; the echo-native logic lives in corsEcho, which SetupMiddlewares wires directly on the default request path (ADR-026, no per-request baton).
func IPPreGuard ¶ added in v0.9.0
func IPPreGuard(threshold int) 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.
The returned MiddlewareFunc is the framework-neutral (echo-free) form; the echo-native logic lives in ipPreGuardEcho, which SetupMiddlewares wires directly on the default request path (ADR-026, no per-request baton).
func LoggerWithConfig ¶ added in v0.13.0
func LoggerWithConfig(log logger.Logger, cfg LoggerConfig) 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.
The returned MiddlewareFunc is the framework-neutral (echo-free) form; the echo-native logic lives in loggerWithConfigEcho, which SetupMiddlewares wires directly on the default request path (ADR-026, no per-request baton).
func PerformanceStats ¶
func PerformanceStats() 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.
The returned MiddlewareFunc is the framework-neutral (echo-free) form; the echo-native logic lives in performanceStatsEcho.
func RateLimit ¶
func RateLimit(requestsPerSecond int) 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.
The returned MiddlewareFunc is the framework-neutral (echo-free) form; the echo-native logic lives in rateLimitEcho, which SetupMiddlewares wires directly on the default request path (ADR-026, no per-request baton).
func RequestEnrich ¶ added in v0.41.0
func RequestEnrich() MiddlewareFunc
RequestEnrich combines the two adjacent pure-value request enrichers — trace-context injection (TraceContext) and per-request operation counters (PerformanceStats) — into a single middleware that performs ONE Request.WithContext clone instead of two. The standalone TraceContext() and PerformanceStats() middlewares remain exported for callers that register them individually; SetupMiddlewares wires this combined form on the hot path.
Behavior is the union of both originals: the resolved trace ID and any inbound W3C trace headers are attached for outbound propagation, and the shared AMQP/DB counters are seeded. TraceContext's canceled-context early-return is adopted so an already-canceled inbound request short-circuits before any enrichment.
It also installs the per-request lease scope (ADR-032): per-tenant resource handles borrowed via deps.DB/Cache/Messaging during the request register their release here and are released when the handler chain unwinds, so a handle evicted mid-request is not closed under the active request. The scope is folded into the existing Request.WithContext clone so it adds no extra per-request allocation, and its release slice stays nil until the first borrow (a request touching no managed resource pays nothing). Registered early in SetupMiddlewares so ReleaseAll runs after the handler and every inner middleware.
The returned MiddlewareFunc is the framework-neutral (echo-free) form; the echo-native logic lives in requestEnrichEcho, which SetupMiddlewares wires directly on the default request path (ADR-026, no per-request baton).
func RequestIDMiddleware ¶ added in v0.37.0
func RequestIDMiddleware() MiddlewareFunc
RequestIDMiddleware reads the inbound X-Request-ID header, validates it against requestIDPattern, and sets the response header to either the validated value or a freshly generated UUID. It MUST replace Echo's stock middleware.RequestID() because that middleware echoes the inbound header verbatim with no validation, which:
- Reflects attacker-controlled bytes back to the client (the response header travels on the wire and lands in CDN logs and browser tools).
- Pre-populates the response header before any framework code runs, defeating downstream validation by getTraceID/safeGetRequestID that would otherwise trust the response-header value.
Register this BEFORE TraceContext and any logger/rate-limit middleware so the rest of the stack sees a sanitized value.
The returned MiddlewareFunc is the framework-neutral (echo-free) form; the echo-native logic lives in requestIDMiddlewareEcho, which SetupMiddlewares wires directly on the default request path (ADR-026, no per-request baton).
func TenantMiddleware ¶ added in v0.9.0
func TenantMiddleware(resolver multitenant.TenantResolver, skipper SkipperFunc) 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.
The returned MiddlewareFunc is the framework-neutral (echo-free) form; the echo-native logic lives in tenantMiddlewareEcho, which SetupMiddlewares wires directly on the default request path (ADR-026, no per-request baton).
func Timeout ¶ added in v0.13.0
func Timeout(duration time.Duration) 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.
The returned MiddlewareFunc is the framework-neutral (echo-free) form; the echo-native logic lives in timeoutEcho, which SetupMiddlewares wires directly on the default request path (ADR-026, no per-request baton).
func Timing ¶
func Timing() 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.
The returned MiddlewareFunc is the framework-neutral (echo-free) form; the echo-native logic lives in timingEcho, which SetupMiddlewares wires directly on the default request path (ADR-026, no per-request baton).
func TraceContext ¶ added in v0.3.0
func TraceContext() 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.
The returned MiddlewareFunc is the framework-neutral (echo-free) form; the echo-native logic lives in traceContextEcho.
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 ResultMetaProvider 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 PathParam ¶ added in v0.46.0
PathParam is one matched path parameter. Ordered slices preserve route-template order.
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 ResultEnvelopeProvider ¶ added in v0.36.0
type ResultEnvelopeProvider interface {
ResultEnvelope() (status int, headers http.Header, data any, meta map[string]any)
}
ResultEnvelopeProvider is the alternative to ResultMetaProvider for handlers that want to contribute extra entries (pagination totals, deprecation notices, etc.) to the response envelope's meta map. The two interfaces have disjoint method sets (ResultEnvelope vs ResultMeta) and ResultEnvelopeProvider does NOT embed ResultMetaProvider — types wanting to be visible to legacy ResultMetaProvider-aware code (e.g. third-party middleware) must implement both methods explicitly. ResultWithMeta[R] does so as the reference example.
The framework merges the returned meta map with its own keys (timestamp, traceId); reservedMetaKeys are always authoritative — handler values for those keys are dropped with a structured WARN.
The framework dispatcher checks ResultEnvelopeProvider BEFORE ResultMetaProvider so a type satisfying both routes through the envelope path. Maintainers MUST preserve that ordering at every dispatch site (server.handleResponse, server.handleRawResponse, JOSE outbound) or ResultWithMeta would silently lose its meta payload.
On JOSE-protected routes, ResultEnvelopeProvider causes the sealed body to ship an envelope shape ({"data": ..., "meta": ...}) instead of bare data. In raw-response mode (WithRawResponse), the meta map is silently dropped — only data is serialized.
type ResultMetaProvider ¶ added in v0.26.0
ResultMetaProvider exposes status, headers, and payload for successful responses.
type ResultWithMeta ¶ added in v0.36.0
ResultWithMeta is a generic success wrapper that carries handler-supplied envelope meta alongside the standard status/headers/data. The framework merges Meta into the response envelope's meta map, with timestamp and traceId remaining framework-managed and authoritative (handler values for those keys are dropped during merge).
Implements both ResultEnvelopeProvider (preferred by the framework dispatcher) and ResultMetaProvider (so third-party middleware that type-asserts the older interface keeps working — meta is dropped on that path).
func NewResultWithMeta ¶ added in v0.36.0
func NewResultWithMeta[R any](status int, data R, meta map[string]any) ResultWithMeta[R]
NewResultWithMeta is a convenience constructor for ResultWithMeta.
func (ResultWithMeta[R]) ResultEnvelope ¶ added in v0.36.0
func (r ResultWithMeta[R]) ResultEnvelope() (status int, headers http.Header, data any, meta map[string]any)
ResultEnvelope implements ResultEnvelopeProvider for ResultWithMeta[R].
func (ResultWithMeta[R]) ResultMeta ¶ added in v0.36.0
func (r ResultWithMeta[R]) ResultMeta() (status int, headers http.Header, data any)
ResultMeta implements ResultMetaProvider for ResultWithMeta[R]. Provided so consumers that only type-assert ResultMetaProvider keep functioning; on that path Meta is dropped — handlers wanting envelope-meta semantics must reach a ResultEnvelopeProvider-aware writer.
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 (empty for raw routes)
Package string // Go package path
RequestType reflect.Type // Request type T from HandlerFunc[T, R]; nil for raw routes
ResponseType reflect.Type // Response type R from HandlerFunc[T, R]; nil for raw routes
Middleware []string // Applied middleware names
Tags []string // Optional grouping tags
Summary string // Optional summary from comments
Description string // Optional description from comments
RawResponse bool // If true, bypass APIResponse envelope (for Strangler Fig migration)
InboundJOSE *jose.Policy // Resolved at registration time from request type's jose: tag; nil for raw routes
OutboundJOSE *jose.Policy // Resolved at registration time from response type's jose: tag; nil for raw routes
}
RouteDescriptor captures metadata about a registered route.
Routes registered through the raw RouteRegistrar.Add path (as opposed to the typed server.GET/POST helpers) carry only method/path/handler metadata: RequestType, ResponseType, InboundJOSE, and OutboundJOSE are nil, and ModuleName is empty, because a raw handler exposes no request/response models. Consumers iterating the registry must nil-check those fields.
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 WithRawResponse ¶ added in v0.25.0
func WithRawResponse() RouteOption
WithRawResponse configures the route to bypass the standard APIResponse envelope, returning the handler's response directly as JSON. Useful for Strangler Fig migrations where legacy endpoints must return their original response format.
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 Handler, middleware ...MiddlewareFunc)
Group(prefix string, middleware ...MiddlewareFunc) RouteRegistrar
Use(middleware ...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 wrap Echo groups internally; the public surface is echo-free — handlers are server.Handler and middleware is server.MiddlewareFunc.
Add does not return a route handle: the value was never consumed anywhere and exposing echo.RouteInfo would re-introduce the leak this abstraction removes.
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) ModuleGroup ¶ added in v0.5.0
func (s *Server) ModuleGroup() RouteRegistrar
ModuleGroup returns a route registrar with the base path applied for module route registration. If no base path is configured, it returns a registrar with empty prefix.
func (*Server) RegisterReadyHandler ¶ added in v0.9.0
RegisterReadyHandler overrides the readiness endpoint handler with a go-bricks Handler. Passing nil restores the default handler. The handler is adapted to the engine once here.
func (*Server) RootGroup ¶ added in v0.45.0
func (s *Server) RootGroup() RouteRegistrar
RootGroup returns a route registrar rooted at the engine with NO base path applied. It is the registration surface for framework-internal endpoints that must sit at the URL root regardless of server.path.base — e.g. the debug/system endpoints. It replaces the former Echo() accessor for that internal need without exposing the engine.
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 decides whether middleware processing is skipped for a request. It receives the stdlib *http.Request — all a skip decision needs — so application code never names an echo type and the decision never depends on per-request state that may be unpopulated.
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 StackTracer ¶ added in v0.30.0
type StackTracer interface {
StackTrace() []string
}
StackTracer is implemented by errors that carry a captured stack trace. The formatter uses this interface to surface frames in the response when running in development. *BaseAPIError satisfies it, and every wrapper type (NotFoundError, BadRequestError, …) inherits it via method promotion.
type TestContextOption ¶ added in v0.47.0
type TestContextOption func(*HandlerContext)
TestContextOption customizes a HandlerContext built by NewHandlerContextForTest. It seeds pre-routing state the engine would otherwise populate during matching, so unit tests can exercise code that reads that state without standing up a router. Test-support only: options are applied at test construction, never on a live request context.
func WithRouteTemplate ¶ added in v0.47.0
func WithRouteTemplate(template string) TestContextOption
WithRouteTemplate stamps the matched route template so RouteTemplate() reports it on an otherwise-unrouted test context (which never routes and would report ""). On a live request the router owns this value; the option is reachable only through the test constructor, so it cannot mutate a routed context's identity. See issue #639.
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.