server

package
v0.14.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 27, 2025 License: MIT Imports: 27 Imported by: 0

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

View Source
const (
	BurstMultiplier  = 2
	RateLimitCleanup = time.Minute * 3
)
View Source
const (
	// IPPreGuardCleanup defines how long to keep IP buckets in memory after last use
	IPPreGuardCleanup = time.Minute * 5
)
View Source
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

View Source
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

func EscalateSeverity(c echo.Context, 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() {
    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[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 Logger deprecated

func Logger(log logger.Logger, healthPath, readyPath string) echo.MiddlewareFunc

Logger returns a request logging middleware using the default configuration. It logs HTTP requests with OpenTelemetry semantic conventions and dual-mode logging support.

Deprecated: Use LoggerWithConfig for more control over logging behavior.

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.

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

type HandlerContext struct {
	Echo   echo.Context
	Config *config.Config
}

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 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.

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

type Result[R any] struct {
	Data    R
	Status  int
	Headers http.Header
}

Result is a generic success wrapper allowing handlers to customize status and headers while preserving type safety of the response payload.

func Accepted added in v0.3.0

func Accepted[R any](data R) Result[R]

Accepted returns a 202 Accepted Result for the given data

func Created added in v0.3.0

func Created[R any](data R) Result[R]

Created returns a 201 Created Result for the given data

func NewResult added in v0.3.0

func NewResult[R any](status int, data R) Result[R]

NewResult is a convenience constructor for Result.

func (Result[R]) ResultMeta added in v0.3.0

func (r Result[R]) ResultMeta() (status int, headers http.Header, data any)

ResultMeta implements ResultLike for Result[R].

type ResultLike added in v0.3.0

type ResultLike interface {
	ResultMeta() (status int, headers http.Header, data any)
}

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

func New(cfg *config.Config, log logger.Logger) *Server

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

func (s *Server) Echo() *echo.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.

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the HTTP server with the given context. It waits for existing connections to finish within the context timeout.

func (*Server) Start

func (s *Server) Start() error

Start starts the HTTP server and begins accepting requests. It blocks until the server is shut down or encounters an error.

type ServiceUnavailableError added in v0.3.0

type ServiceUnavailableError struct {
	*BaseAPIError
}

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 SkipperFunc added in v0.9.0

type SkipperFunc func(c echo.Context) bool

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.

type UnauthorizedError added in v0.3.0

type UnauthorizedError struct {
	*BaseAPIError
}

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

func (v *Validator) GetValidator() *validator.Validate

GetValidator returns the underlying validator instance.

func (*Validator) Validate

func (v *Validator) Validate(i any) error

Validate performs validation on the provided struct and returns any validation errors.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL