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. 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 RegisterGenericRoute[T any, U any](r *Router, route RouteConfig[T, U])
- type Codec
- type GenericHandler
- type HTTPError
- type Middleware
- type PrometheusConfig
- type RouteConfig
- type RouteConfigBase
- type Router
- type RouterConfig
- 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 RegisterGenericRoute ¶
func RegisterGenericRoute[T any, U any](r *Router, route RouteConfig[T, U])
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.
Types ¶
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 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 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) Middleware
LoggingMiddleware is a middleware that logs HTTP requests and responses. It captures the request method, path, status code, and duration.
type PrometheusConfig ¶
type PrometheusConfig struct {
Registry interface{} // Prometheus registry (prometheus.Registerer)
Namespace string // Namespace for metrics
Subsystem string // Subsystem for metrics
EnableLatency bool // Enable latency metrics
EnableThroughput bool // Enable throughput metrics
EnableQPS bool // Enable queries per second metrics
EnableErrors bool // Enable error metrics
}
PrometheusConfig defines the configuration for Prometheus metrics. It allows customization of how metrics are collected and labeled.
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 RequireAuth bool // Whether this route requires authentication Timeout time.Duration // Override timeout for this specific route MaxBodySize int64 // Override max body size 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 }
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
RequireAuth bool // Whether this route requires authentication
Timeout time.Duration // Override timeout for this specific route
MaxBodySize int64 // Override max body size 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 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(config RouterConfig) *Router
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) RegisterRoute ¶
func (r *Router) 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.
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
EnableMetrics bool // Enable metrics collection
EnableTracing bool // Enable distributed tracing
PrometheusConfig *PrometheusConfig // Prometheus metrics configuration (optional)
SubRouters []SubRouterConfig // Sub-routers with their own configurations
Middlewares []common.Middleware // Global middlewares applied to all routes
}
RouterConfig defines the global configuration for the router. It includes settings for logging, timeouts, metrics, and middleware.
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
Routes []RouteConfigBase // Routes in this sub-router
Middlewares []common.Middleware // Middlewares applied to all routes in this sub-router
}
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.