Documentation
¶
Overview ¶
Package router provides a flexible and feature-rich HTTP routing framework. It supports middleware, sub-routers, generic handlers, and various configuration options.
Package router provides a flexible and feature-rich HTTP routing framework.
Package router provides a flexible and feature-rich HTTP routing framework. It supports middleware, sub-routers, generic handlers, and various configuration options.
Index ¶
- Constants
- func GetParam(r *http.Request, name string) string
- func GetParams(r *http.Request) httprouter.Params
- func GetUser[T comparable, U any](r *http.Request) (U, bool)
- func GetUserID[T comparable, U any](r *http.Request) (T, bool)
- func RegisterGenericRoute[Req any, Resp any, UserID comparable, User any](r *Router[UserID, User], route RouteConfig[Req, Resp])
- func RegisterGenericRouteWithSubRouter[Req any, Resp any, UserID comparable, User any](sr *SubRouterConfig, route RouteConfig[Req, Resp])
- func RegisterSubRouterWithSubRouter(parent *SubRouterConfig, child SubRouterConfig)
- type AuthLevel
- type Codec
- type GenericHandler
- type GenericRouteConfig
- type GenericRouteConfigs
- type GenericRouteRegistrar
- type HTTPError
- type MetricsConfig
- type Middleware
- type PrometheusConfig
- type RouteConfig
- type RouteConfigBase
- type Router
- func (r *Router[T, U]) EnsureRouterContext(ctx context.Context) (*RouterContext[T, U], context.Context)
- func (r *Router[T, U]) GetFlagFromContext(ctx context.Context, name string) (bool, bool)
- func (r *Router[T, U]) GetRouterContext(ctx context.Context) (*RouterContext[T, U], bool)
- func (r *Router[T, U]) GetUserFromContext(ctx context.Context) (*U, bool)
- func (r *Router[T, U]) GetUserIDFromContext(ctx context.Context) (T, bool)
- func (r *Router[T, U]) NewRouterContext() *RouterContext[T, U]
- func (r *Router[T, U]) RegisterRoute(route RouteConfigBase)
- func (r *Router[T, U]) RegisterSubRouter(sr SubRouterConfig)
- func (r *Router[T, U]) ServeHTTP(w http.ResponseWriter, req *http.Request)
- func (r *Router[T, U]) Shutdown(ctx context.Context) error
- func (r *Router[T, U]) WithFlag(ctx context.Context, name string, value bool) context.Context
- func (r *Router[T, U]) WithRouterContext(ctx context.Context, rc *RouterContext[T, U]) context.Context
- func (r *Router[T, U]) WithUser(ctx context.Context, user *U) context.Context
- func (r *Router[T, U]) WithUserID(ctx context.Context, userID T) context.Context
- type RouterConfig
- type RouterContext
- type SourceType
- type SubRouterConfig
Constants ¶
const ( // ParamsKey is the key used to store httprouter.Params in the request context. // This allows route parameters to be accessed from handlers and middleware. ParamsKey contextKey = "params" )
Variables ¶
This section is empty.
Functions ¶
func GetParam ¶
GetParam retrieves a specific parameter from the request context. It's a convenience function that combines GetParams and ByName.
func GetParams ¶
func GetParams(r *http.Request) httprouter.Params
GetParams retrieves the httprouter.Params from the request context. This allows handlers to access route parameters extracted from the URL.
func GetUserID ¶ added in v1.0.0
func GetUserID[T comparable, U any](r *http.Request) (T, bool)
GetUserID retrieves the user ID from the request context. Returns the user ID if it exists in the context, the zero value of T otherwise.
func RegisterGenericRoute ¶
func RegisterGenericRoute[Req any, Resp any, UserID comparable, User any](r *Router[UserID, User], route RouteConfig[Req, Resp])
RegisterGenericRoute registers a route with generic request and response types. This is a standalone function rather than a method because Go methods cannot have type parameters. It creates a handler that uses the codec to decode the request and encode the response, applies middleware, and registers the route with the router.
func RegisterGenericRouteWithSubRouter ¶ added in v1.0.7
func RegisterGenericRouteWithSubRouter[Req any, Resp any, UserID comparable, User any](sr *SubRouterConfig, route RouteConfig[Req, Resp])
RegisterGenericRouteWithSubRouter registers a generic route with a SubRouter This is a helper function that creates a GenericRouteConfig and adds it to the SubRouter's GenericRoutes field
func RegisterSubRouterWithSubRouter ¶ added in v1.0.7
func RegisterSubRouterWithSubRouter(parent *SubRouterConfig, child SubRouterConfig)
RegisterSubRouterWithSubRouter registers a nested SubRouter with a parent SubRouter This is a helper function that adds a SubRouter to the parent SubRouter's SubRouters field
Types ¶
type AuthLevel ¶ added in v1.0.0
type AuthLevel int
AuthLevel defines the authentication level for a route. It determines how authentication is handled for the route.
const ( // NoAuth indicates that no authentication is required for the route. // The route will be accessible without any authentication. NoAuth AuthLevel = iota // AuthOptional indicates that authentication is optional for the route. // If authentication credentials are provided, they will be validated and the user // will be added to the request context if valid. If no credentials are provided // or they are invalid, the request will still proceed without a user in the context. AuthOptional // AuthRequired indicates that authentication is required for the route. // If authentication fails, the request will be rejected with a 401 Unauthorized response. // If authentication succeeds, the user will be added to the request context. AuthRequired )
type Codec ¶
type Codec[T any, U any] interface { // Decode extracts and deserializes data from an HTTP request into a value of type T. // It reads the request body and converts it from the wire format (e.g., JSON, Protocol Buffers) // into the appropriate Go type. If the deserialization fails, it returns an error. // The type T represents the request data type. Decode(r *http.Request) (T, error) // Encode serializes a value of type U and writes it to the HTTP response. // It converts the Go value to the wire format (e.g., JSON, Protocol Buffers) and // sets appropriate headers (e.g., Content-Type). If the serialization fails, it returns an error. // The type U represents the response data type. Encode(w http.ResponseWriter, resp U) error }
Codec defines an interface for marshaling and unmarshaling request and response data. It provides methods for decoding request data from an HTTP request and encoding response data to an HTTP response. This allows for different data formats (e.g., JSON, Protocol Buffers). The framework includes implementations for JSON and Protocol Buffers in the codec package.
type GenericHandler ¶
GenericHandler defines a handler function with generic request and response types. It takes an http.Request and a typed request data object, and returns a typed response object and an error. This allows for strongly-typed request and response handling. The type parameters T and U represent the request and response data types respectively. When used with RegisterGenericRoute, the framework automatically handles decoding the request and encoding the response using the specified Codec.
type GenericRouteConfig ¶ added in v1.0.7
type GenericRouteConfig[Req any, Resp any, UserID comparable, User any] struct { Config RouteConfig[Req, Resp] }
GenericRouteConfig is a wrapper for RouteConfig that implements GenericRouteRegistrar It allows storing generic routes with different type parameters in SubRouterConfig
func CreateGenericRouteForSubRouter ¶ added in v1.0.7
func CreateGenericRouteForSubRouter[Req any, Resp any, UserID comparable, User any](route RouteConfig[Req, Resp]) GenericRouteConfig[Req, Resp, UserID, User]
CreateGenericRouteForSubRouter creates a GenericRouteConfig that can be added to a SubRouterConfig's GenericRoutes field This is a helper function to make it easier to register generic routes with SubRouters
func (GenericRouteConfig[Req, Resp, UserID, User]) RegisterWith ¶ added in v1.0.7
func (g GenericRouteConfig[Req, Resp, UserID, User]) RegisterWith(router interface{}, pathPrefix string) error
RegisterWith registers the generic route with the router It implements the GenericRouteRegistrar interface
type GenericRouteConfigs ¶ added in v1.0.7
type GenericRouteConfigs []GenericRouteRegistrar
GenericRouteConfigs is a slice of GenericRouteRegistrar It's used to store multiple generic routes in SubRouterConfig
type GenericRouteRegistrar ¶ added in v1.0.7
GenericRouteRegistrar is an interface for registering generic routes It's used to store generic routes with different type parameters in SubRouterConfig
type HTTPError ¶
type HTTPError struct {
StatusCode int // HTTP status code (e.g., 400, 404, 500)
Message string // Error message to be sent in the response body
}
HTTPError represents an HTTP error with a status code and message. It can be used to return specific HTTP errors from handlers. When returned from a handler, the router will use the status code and message to generate an appropriate HTTP response. This allows handlers to control the exact error response sent to clients.
func NewHTTPError ¶
NewHTTPError creates a new HTTPError with the specified status code and message. It's a convenience function for creating HTTP errors in handlers.
type MetricsConfig ¶ added in v1.0.3
type MetricsConfig struct {
// Collector is the metrics collector to use.
// If nil, a default collector will be used if metrics are enabled.
Collector interface{} // metrics.Collector
// Exporter is the metrics exporter to use.
// If nil, a default exporter will be used if metrics are enabled.
Exporter interface{} // metrics.Exporter
// MiddlewareFactory is the factory for creating metrics middleware.
// If nil, a default middleware factory will be used if metrics are enabled.
MiddlewareFactory interface{} // metrics.MiddlewareFactory
// Namespace for metrics.
Namespace string
// Subsystem for metrics.
Subsystem string
// EnableLatency enables latency metrics.
EnableLatency bool
// EnableThroughput enables throughput metrics.
EnableThroughput bool
// EnableQPS enables queries per second metrics.
EnableQPS bool
// EnableErrors enables error metrics.
EnableErrors bool
}
MetricsConfig defines the configuration for metrics collection. It allows customization of how metrics are collected and exposed.
type Middleware ¶
type Middleware = common.Middleware
Middleware is an alias for common.Middleware. It represents a function that wraps an http.Handler to provide additional functionality.
func LoggingMiddleware ¶
func LoggingMiddleware(logger *zap.Logger, enableTraceID bool) Middleware
LoggingMiddleware is a middleware that logs HTTP requests and responses. It captures the request method, path, status code, and duration. If enableTraceID is true, it will include the trace ID in the logs if present.
type PrometheusConfig ¶
type PrometheusConfig struct{}
PrometheusConfig is removed in favor of MetricsConfig with v2 metrics system. This type is kept for reference but should not be used. Deprecated: Use MetricsConfig instead.
type RouteConfig ¶
type RouteConfig[T any, U any] struct { Path string // Route path (will be prefixed with sub-router path prefix if applicable) Methods []string // HTTP methods this route handles AuthLevel AuthLevel // Authentication level for this route (NoAuth, AuthOptional, or AuthRequired) Timeout time.Duration // Override timeout for this specific route MaxBodySize int64 // Override max body size for this specific route RateLimit *middleware.RateLimitConfig[any, any] // Rate limit for this specific route Codec Codec[T, U] // Codec for marshaling/unmarshaling request and response Handler GenericHandler[T, U] // Generic handler function Middlewares []common.Middleware // Middlewares applied to this specific route SourceType SourceType // How to retrieve request data (defaults to Body) SourceKey string // Query parameter name (only used for query parameters) CacheResponse bool // Whether to cache responses for this route CacheKeyPrefix string // Prefix for cache keys to avoid collisions }
RouteConfig defines a route with generic request and response types. It extends RouteConfigBase with type parameters for request and response data, allowing for strongly-typed handlers and automatic marshaling/unmarshaling.
type RouteConfigBase ¶
type RouteConfigBase struct {
Path string // Route path (will be prefixed with sub-router path prefix if applicable)
Methods []string // HTTP methods this route handles
AuthLevel AuthLevel // Authentication level for this route (NoAuth, AuthOptional, or AuthRequired)
Timeout time.Duration // Override timeout for this specific route
MaxBodySize int64 // Override max body size for this specific route
RateLimit *middleware.RateLimitConfig[any, any] // Rate limit for this specific route
Handler http.HandlerFunc // Standard HTTP handler function
Middlewares []common.Middleware // Middlewares applied to this specific route
}
RouteConfigBase defines the base configuration for a route without generics. It includes settings for path, HTTP methods, authentication, timeouts, and middleware.
type Router ¶
type Router[T comparable, U any] struct { // contains filtered or unexported fields }
Router is the main router struct that implements http.Handler. It provides routing, middleware support, graceful shutdown, and other features.
func NewRouter ¶
func NewRouter[T comparable, U any](config RouterConfig, authFunction func(context.Context, string) (U, bool), userIdFromuserFunction func(U) T) *Router[T, U]
NewRouter creates a new Router with the given configuration. It initializes the underlying httprouter, sets up logging, and registers routes from sub-routers.
func (*Router[T, U]) EnsureRouterContext ¶ added in v1.0.9
func (r *Router[T, U]) EnsureRouterContext(ctx context.Context) (*RouterContext[T, U], context.Context)
EnsureRouterContext retrieves or creates a router context
func (*Router[T, U]) GetFlagFromContext ¶ added in v1.0.9
GetFlagFromContext retrieves a flag from the router context
func (*Router[T, U]) GetRouterContext ¶ added in v1.0.9
func (r *Router[T, U]) GetRouterContext(ctx context.Context) (*RouterContext[T, U], bool)
GetRouterContext retrieves the router context from a request context
func (*Router[T, U]) GetUserFromContext ¶ added in v1.0.9
GetUserFromContext retrieves a user from the router context
func (*Router[T, U]) GetUserIDFromContext ¶ added in v1.0.9
GetUserIDFromContext retrieves a user ID from the router context
func (*Router[T, U]) NewRouterContext ¶ added in v1.0.9
func (r *Router[T, U]) NewRouterContext() *RouterContext[T, U]
NewRouterContext creates a new router context
func (*Router[T, U]) RegisterRoute ¶
func (r *Router[T, U]) RegisterRoute(route RouteConfigBase)
RegisterRoute registers a route with the router. It creates a handler with all middlewares applied and registers it with the underlying httprouter. For generic routes with type parameters, use RegisterGenericRoute function instead.
func (*Router[T, U]) RegisterSubRouter ¶ added in v1.0.7
func (r *Router[T, U]) RegisterSubRouter(sr SubRouterConfig)
RegisterSubRouter registers a sub-router with the router. It applies the sub-router's path prefix to all routes and registers them with the router. This is an exported wrapper for the unexported registerSubRouter method.
func (*Router[T, U]) ServeHTTP ¶
func (r *Router[T, U]) ServeHTTP(w http.ResponseWriter, req *http.Request)
ServeHTTP implements the http.Handler interface. It handles HTTP requests by applying metrics and tracing if enabled, and then delegating to the underlying httprouter.
func (*Router[T, U]) Shutdown ¶
Shutdown gracefully shuts down the router. It stops accepting new requests and waits for existing requests to complete. If the context is canceled before all requests complete, it returns the context's error.
func (*Router[T, U]) WithRouterContext ¶ added in v1.0.9
func (r *Router[T, U]) WithRouterContext(ctx context.Context, rc *RouterContext[T, U]) context.Context
WithRouterContext adds or updates the router context in the request context
type RouterConfig ¶
type RouterConfig struct {
Logger *zap.Logger // Logger for all router operations
GlobalTimeout time.Duration // Default response timeout for all routes
GlobalMaxBodySize int64 // Default maximum request body size in bytes
GlobalRateLimit *middleware.RateLimitConfig[any, any] // Default rate limit for all routes
IPConfig *middleware.IPConfig // Configuration for client IP extraction
EnableMetrics bool // Enable metrics collection
EnableTracing bool // Enable distributed tracing
EnableTraceID bool // Enable trace ID logging
PrometheusConfig *PrometheusConfig // Prometheus metrics configuration (optional, deprecated)
MetricsConfig *MetricsConfig // Metrics configuration (optional)
SubRouters []SubRouterConfig // Sub-routers with their own configurations
Middlewares []common.Middleware // Global middlewares applied to all routes
AddUserObjectToCtx bool // Add user object to context
CacheGet func(string) ([]byte, bool) // Function to retrieve cached responses
CacheSet func(string, []byte) error // Function to store responses in the cache
CacheKeyPrefix string // Prefix for cache keys to avoid collisions
}
RouterConfig defines the global configuration for the router. It includes settings for logging, timeouts, metrics, and middleware.
type RouterContext ¶ added in v1.0.9
type RouterContext[T comparable, U any] struct { // User ID and User object storage UserID T User *U Flags map[string]bool // contains filtered or unexported fields }
RouterContext holds all values that a router instance adds to request contexts It allows storing multiple types of values with only a single level of context nesting
type SourceType ¶ added in v1.0.5
type SourceType int
SourceType defines where to retrieve request data from. It determines how the request data is extracted and decoded.
const ( // Body retrieves data from the request body (default). // The request body is read and passed directly to the codec for decoding. Body SourceType = iota // Base64QueryParameter retrieves data from a base64-encoded query parameter. // The query parameter value is decoded from base64 before being passed to the codec. Base64QueryParameter // Base62QueryParameter retrieves data from a base62-encoded query parameter. // The query parameter value is decoded from base62 before being passed to the codec. Base62QueryParameter // Base64PathParameter retrieves data from a base64-encoded path parameter. // The path parameter value is decoded from base64 before being passed to the codec. Base64PathParameter // Base62PathParameter retrieves data from a base62-encoded path parameter. // The path parameter value is decoded from base62 before being passed to the codec. Base62PathParameter )
type SubRouterConfig ¶
type SubRouterConfig struct {
PathPrefix string // Common path prefix for all routes in this sub-router
TimeoutOverride time.Duration // Override global timeout for all routes in this sub-router
MaxBodySizeOverride int64 // Override global max body size for all routes in this sub-router
RateLimitOverride *middleware.RateLimitConfig[any, any] // Override global rate limit for all routes in this sub-router
Routes []RouteConfigBase // Routes in this sub-router
Middlewares []common.Middleware // Middlewares applied to all routes in this sub-router
CacheResponse bool // Whether to cache responses for routes in this sub-router
CacheKeyPrefix string // Prefix for cache keys to avoid collisions
// GenericRoutes is an interface{} that will be cast to the appropriate type in registerSubRouter
// It allows storing generic routes with different type parameters
GenericRoutes interface{} // Generic routes in this sub-router
// SubRouters is a slice of nested sub-routers
// This allows for creating a hierarchy of sub-routers
SubRouters []SubRouterConfig // Nested sub-routers
}
SubRouterConfig defines configuration for a group of routes with a common path prefix. This allows for organizing routes into logical groups and applying shared configuration.