Documentation
¶
Overview ¶
Package middleware provides a collection of HTTP middleware components for the SRouter framework.
Package middleware provides a collection of HTTP middleware components for the SRouter framework. These middleware components can be used to add functionality such as logging, recovery from panics, authentication, request timeouts, and more to your HTTP handlers.
Package middleware provides a collection of HTTP middleware components for the SRouter framework.
Package middleware provides a collection of HTTP middleware components for the SRouter framework.
Package middleware provides a collection of HTTP middleware components for the SRouter framework.
Index ¶
- Variables
- func Authentication[T comparable, U any](authFunc func(*http.Request) (T, bool)) common.Middleware
- func AuthenticationBool[T comparable, U any](authFunc func(*http.Request) bool, flagName string) common.Middleware
- func AuthenticationWithProvider[T comparable, U any](provider AuthProvider[T], logger *zap.Logger) common.Middleware
- func AuthenticationWithUser[T comparable, U any](authFunc func(*http.Request) (*U, error)) common.Middleware
- func AuthenticationWithUserProvider[T comparable, U any](provider UserAuthProvider[U], logger *zap.Logger) common.Middleware
- func CreateTraceMiddleware[T comparable, U any](generator *IDGenerator) common.Middleware
- func NewAPIKeyMiddleware[T comparable, U any](validKeys map[string]T, header, query string, logger *zap.Logger) common.Middleware
- func NewAPIKeyWithUserMiddleware[T comparable, U any](getUserFunc func(key string) (*U, error), header, query string, ...) common.Middleware
- func NewBearerTokenMiddleware[T comparable, U any](validTokens map[string]T, logger *zap.Logger) common.Middleware
- func NewBearerTokenValidatorMiddleware[T comparable, U any](validator func(string) (T, bool), logger *zap.Logger) common.Middleware
- func NewBearerTokenWithUserMiddleware[T comparable, U any](getUserFunc func(token string) (*U, error), logger *zap.Logger) common.Middleware
- func RateLimit[T comparable, U any](config *common.RateLimitConfig[T, U], limiter common.RateLimiter, ...) common.Middleware
- type APIKeyProvider
- type APIKeyUserAuthProvider
- type AuthProvider
- type BasicUserAuthProvider
- type BearerTokenProvider
- type BearerTokenUserAuthProvider
- type GormTransactionWrapper
- type IDGenerator
- type Middleware
- type UberRateLimiter
- type UserAuthProvider
Constants ¶
This section is empty.
Variables ¶
var ( // From middleware.go Recovery = recovery MaxBodySize = maxBodySize Timeout = timeout )
Public middleware constructors exposed via variables. The actual implementations are kept private within their respective files.
Functions ¶
func Authentication ¶
func Authentication[T comparable, U any]( authFunc func(*http.Request) (T, bool), ) common.Middleware
Authentication is a middleware that checks if a request is authenticated using a simple auth function. T is the User ID type (comparable), U is the User object type (any). It allows for custom authentication logic to be provided as a simple function.
func AuthenticationBool ¶ added in v1.0.0
func AuthenticationBool[T comparable, U any]( authFunc func(*http.Request) bool, flagName string, ) common.Middleware
AuthenticationBool is a middleware that checks if a request is authenticated using a simple auth function. It allows for custom authentication logic to be provided as a simple function that returns a boolean. It adds a boolean flag to the SRouterContext if authentication is successful. T is the User ID type (comparable), U is the User object type (any).
func AuthenticationWithProvider ¶
func AuthenticationWithProvider[T comparable, U any]( provider AuthProvider[T], logger *zap.Logger, ) common.Middleware
AuthenticationWithProvider is a middleware that checks if a request is authenticated using the provided auth provider. If authentication fails, it returns a 401 Unauthorized response. This middleware allows for flexible authentication mechanisms by accepting any AuthProvider implementation. T is the User ID type (comparable), U is the User object type (any).
This implementation uses the SRouterContext approach to store the authenticated user ID, which avoids deep nesting of context values by using a single wrapper structure. The type parameters allow for type-safe access to the user ID without type assertions.
func AuthenticationWithUser ¶ added in v1.0.0
func AuthenticationWithUser[T comparable, U any]( authFunc func(*http.Request) (*U, error), ) common.Middleware
AuthenticationWithUser is a middleware that uses a custom auth function that returns a user object and adds it to the SRouterContext if authentication is successful. T is the User ID type (comparable), U is the User object type (any).
func AuthenticationWithUserProvider ¶ added in v1.0.0
func AuthenticationWithUserProvider[T comparable, U any]( provider UserAuthProvider[U], logger *zap.Logger, ) common.Middleware
AuthenticationWithUserProvider is a middleware that uses an auth provider that returns a user object and adds it to the SRouterContext if authentication is successful. T is the User ID type (comparable), U is the User object type (any).
func CreateTraceMiddleware ¶ added in v1.1.13
func CreateTraceMiddleware[T comparable, U any](generator *IDGenerator) common.Middleware
CreateTraceMiddleware creates a trace middleware with the provided ID generator. This is the core implementation used by both traceMiddleware and traceMiddlewareWithConfig. It checks for an existing trace ID in the request headers before generating a new one, which allows for trace ID propagation across service calls. It's now generic to accept the UserID (T) and User (U) types from the router.
func NewAPIKeyMiddleware ¶
func NewAPIKeyMiddleware[T comparable, U any]( validKeys map[string]T, header, query string, logger *zap.Logger, ) common.Middleware
NewAPIKeyMiddleware creates a middleware that uses API Key Authentication. T is the User ID type (comparable), U is the User object type (any).
func NewAPIKeyWithUserMiddleware ¶ added in v1.0.0
func NewAPIKeyWithUserMiddleware[T comparable, U any]( getUserFunc func(key string) (*U, error), header, query string, logger *zap.Logger, ) common.Middleware
NewAPIKeyWithUserMiddleware creates a middleware that uses API Key Authentication NewAPIKeyWithUserMiddleware creates a middleware that uses API Key Authentication and returns a user object, adding it to the SRouterContext. T is the User ID type (comparable), U is the User object type (any).
func NewBearerTokenMiddleware ¶
func NewBearerTokenMiddleware[T comparable, U any]( validTokens map[string]T, logger *zap.Logger, ) common.Middleware
NewBearerTokenMiddleware creates a middleware that uses Bearer Token Authentication. T is the User ID type (comparable), U is the User object type (any).
func NewBearerTokenValidatorMiddleware ¶
func NewBearerTokenValidatorMiddleware[T comparable, U any]( validator func(string) (T, bool), logger *zap.Logger, ) common.Middleware
NewBearerTokenValidatorMiddleware creates a middleware that uses Bearer Token Authentication NewBearerTokenValidatorMiddleware creates a middleware that uses Bearer Token Authentication with a custom validator function. T is the User ID type (comparable), U is the User object type (any).
func NewBearerTokenWithUserMiddleware ¶ added in v1.0.0
func NewBearerTokenWithUserMiddleware[T comparable, U any]( getUserFunc func(token string) (*U, error), logger *zap.Logger, ) common.Middleware
NewBearerTokenWithUserMiddleware creates a middleware that uses Bearer Token Authentication NewBearerTokenWithUserMiddleware creates a middleware that uses Bearer Token Authentication and returns a user object, adding it to the SRouterContext. T is the User ID type (comparable), U is the User object type (any).
func RateLimit ¶ added in v1.0.0
func RateLimit[T comparable, U any](config *common.RateLimitConfig[T, U], limiter common.RateLimiter, logger *zap.Logger) common.Middleware
RateLimit creates a middleware that enforces rate limits based on the provided configuration. T is the User ID type (comparable). U is the User object type (any).
IMPORTANT: When using common.StrategyIP, ensure that router.ClientIPMiddleware is applied *before* this middleware in the chain.
Types ¶
type APIKeyProvider ¶
type APIKeyProvider[T comparable] struct { ValidKeys map[string]T // key -> user ID Header string // header name (e.g., "X-API-Key") Query string // query parameter name (e.g., "api_key") }
APIKeyProvider provides API Key Authentication. It can validate API keys provided in a header or query parameter. The type parameter T represents the user ID type, which can be any comparable type.
func (*APIKeyProvider[T]) Authenticate ¶
func (p *APIKeyProvider[T]) Authenticate(r *http.Request) (T, bool)
Authenticate authenticates a request using API Key Authentication. It checks for the API key in either the specified header or query parameter and validates it against the stored valid keys. Returns the user ID if authentication is successful, the zero value of T and false otherwise.
type APIKeyUserAuthProvider ¶ added in v1.0.0
type APIKeyUserAuthProvider[T any] struct { GetUserFunc func(key string) (*T, error) Header string // header name (e.g., "X-API-Key") Query string // query parameter name (e.g., "api_key") }
APIKeyUserAuthProvider provides API Key Authentication with user object return.
func (*APIKeyUserAuthProvider[T]) AuthenticateUser ¶ added in v1.0.0
func (p *APIKeyUserAuthProvider[T]) AuthenticateUser(r *http.Request) (*T, error)
AuthenticateUser authenticates a request using API Key Authentication. It checks for the API key in either the specified header or query parameter and validates it using the GetUserFunc. Returns the user object if authentication is successful, nil and an error otherwise.
type AuthProvider ¶
type AuthProvider[T comparable] interface { // Authenticate authenticates a request and returns the user ID if authentication is successful. // It examines the request for authentication credentials (such as headers, cookies, or query parameters) // and validates them according to the provider's implementation. // Returns the user ID if the request is authenticated, the zero value of T otherwise. Authenticate(r *http.Request) (T, bool) }
AuthProvider defines an interface for authentication providers. Different authentication mechanisms can implement this interface to be used with the AuthenticationWithProvider middleware. The framework includes several implementations: BasicAuthProvider, BearerTokenProvider, and APIKeyProvider. The type parameter T represents the user ID type, which can be any comparable type.
type BasicUserAuthProvider ¶ added in v1.0.0
type BasicUserAuthProvider[T any] struct { GetUserFunc func(username, password string) (*T, error) }
BasicUserAuthProvider provides HTTP Basic Authentication with user object return.
func (*BasicUserAuthProvider[T]) AuthenticateUser ¶ added in v1.0.0
func (p *BasicUserAuthProvider[T]) AuthenticateUser(r *http.Request) (*T, error)
AuthenticateUser authenticates a request using HTTP Basic Authentication. It extracts the username and password from the Authorization header and validates them using the GetUserFunc. Returns the user object if authentication is successful, nil and an error otherwise.
type BearerTokenProvider ¶
type BearerTokenProvider[T comparable] struct { ValidTokens map[string]T // token -> user ID Validator func(token string) (T, bool) // optional token validator }
BearerTokenProvider provides Bearer Token Authentication. It can validate tokens against a predefined map or using a custom validator function. The type parameter T represents the user ID type, which can be any comparable type.
func (*BearerTokenProvider[T]) Authenticate ¶
func (p *BearerTokenProvider[T]) Authenticate(r *http.Request) (T, bool)
Authenticate authenticates a request using Bearer Token Authentication. It extracts the token from the Authorization header and validates it using either the validator function (if provided) or the ValidTokens map. Returns the user ID if authentication is successful, the zero value of T and false otherwise.
type BearerTokenUserAuthProvider ¶ added in v1.0.0
BearerTokenUserAuthProvider provides Bearer Token Authentication with user object return.
func (*BearerTokenUserAuthProvider[T]) AuthenticateUser ¶ added in v1.0.0
func (p *BearerTokenUserAuthProvider[T]) AuthenticateUser(r *http.Request) (*T, error)
AuthenticateUser authenticates a request using Bearer Token Authentication. It extracts the token from the Authorization header and validates it using the GetUserFunc. Returns the user object if authentication is successful, nil and an error otherwise.
type GormTransactionWrapper ¶ added in v1.1.5
GormTransactionWrapper wraps a *gorm.DB instance to implement the scontext.DatabaseTransaction interface. This adapter allows GORM transactions to be used with SRouter's context-based transaction management. It's necessary because GORM's methods return *gorm.DB for method chaining, while the DatabaseTransaction interface expects simple error returns. This wrapper bridges that gap, making GORM transactions compatible with SRouter's transaction middleware patterns.
func NewGormTransactionWrapper ¶ added in v1.1.5
func NewGormTransactionWrapper(tx *gorm.DB) *GormTransactionWrapper
NewGormTransactionWrapper creates a new GormTransactionWrapper instance. It takes a GORM database instance (typically a transaction) and returns a wrapper that implements the scontext.DatabaseTransaction interface. This is typically used by database middleware when starting a new transaction.
func (*GormTransactionWrapper) Commit ¶ added in v1.1.5
func (w *GormTransactionWrapper) Commit() error
Commit commits the wrapped GORM transaction. It implements the DatabaseTransaction interface. Returns an error if the transaction is nil or if the commit fails.
func (*GormTransactionWrapper) GetDB ¶ added in v1.1.5
func (w *GormTransactionWrapper) GetDB() *gorm.DB
GetDB returns the underlying *gorm.DB instance. This allows handlers to access the full GORM API when needed, while still benefiting from SRouter's transaction management. The returned instance is typically a transaction, not the main DB connection.
func (*GormTransactionWrapper) Rollback ¶ added in v1.1.5
func (w *GormTransactionWrapper) Rollback() error
Rollback rolls back the wrapped GORM transaction. It implements the DatabaseTransaction interface. Returns an error if the transaction is nil or if the rollback fails.
func (*GormTransactionWrapper) RollbackTo ¶ added in v1.1.5
func (w *GormTransactionWrapper) RollbackTo(name string) error
RollbackTo rolls back the transaction to a previously created savepoint. It implements the DatabaseTransaction interface. Only the changes made after the savepoint will be undone. Returns an error if the transaction is nil or if the rollback fails.
func (*GormTransactionWrapper) SavePoint ¶ added in v1.1.5
func (w *GormTransactionWrapper) SavePoint(name string) error
SavePoint creates a savepoint within the transaction with the given name. It implements the DatabaseTransaction interface. Savepoints allow partial rollbacks within a transaction. Returns an error if the transaction is nil or if creating the savepoint fails.
type IDGenerator ¶ added in v1.1.2
type IDGenerator struct {
// contains filtered or unexported fields
}
IDGenerator provides efficient generation of trace IDs by precomputing them. It maintains a buffer of pre-generated UUIDs in a channel, with a background goroutine continuously replenishing the buffer. This approach significantly reduces the latency of ID generation in the request path.
func NewIDGenerator ¶ added in v1.1.2
func NewIDGenerator(bufferSize int) *IDGenerator
NewIDGenerator creates a new IDGenerator with the specified buffer size. The buffer size determines how many pre-generated IDs are kept ready. A larger buffer size provides more resilience against traffic spikes but uses more memory. The background generator starts immediately.
func (*IDGenerator) GetID ¶ added in v1.1.2
func (g *IDGenerator) GetID() string
GetID returns a precomputed UUID from the buffer channel. This method blocks if the buffer is empty, waiting until a new ID is generated by the background goroutine. In normal operation, the buffer should never be empty if sized appropriately for your traffic patterns. Use GetIDNonBlocking for non-blocking behavior.
func (*IDGenerator) GetIDNonBlocking ¶ added in v1.1.2
func (g *IDGenerator) GetIDNonBlocking() string
GetIDNonBlocking attempts to get a precomputed UUID without blocking. If the buffer is empty, it generates a new UUID immediately in the calling goroutine. This ensures requests are never delayed waiting for an ID, even during extreme traffic spikes that exhaust the buffer. This is the preferred method for request-path ID generation.
func (*IDGenerator) Stop ¶ added in v1.2.13
func (g *IDGenerator) Stop()
Stop signals the background ID generator goroutine to exit. This should be called when shutting down the router to ensure clean termination. It's safe to call Stop multiple times.
type Middleware ¶
type Middleware = common.Middleware
Middleware is an alias for the common.Middleware type. It represents a function that wraps an http.Handler to provide additional functionality.
func Chain ¶
func Chain(middlewares ...Middleware) Middleware
Chain combines multiple middleware functions into a single middleware. The middlewares are applied in the order they appear in the chain: the first middleware in the list will be the outermost wrapper. This means it will be the first to process the request and the last to process the response, following the "onion" model of middleware.
Example:
chain := Chain(logging, auth, rateLimit) // Results in: logging(auth(rateLimit(handler)))
type UberRateLimiter ¶ added in v1.0.0
type UberRateLimiter struct {
// contains filtered or unexported fields
}
UberRateLimiter implements the common.RateLimiter interface using Uber's ratelimit library. It provides a leaky bucket rate limiting algorithm, which smooths out request rates by allowing a steady flow of requests while preventing bursts. The implementation maintains a map of rate limiters, one per unique key.
func NewUberRateLimiter ¶ added in v1.0.0
func NewUberRateLimiter() *UberRateLimiter
NewUberRateLimiter creates a new UberRateLimiter instance. The returned limiter uses the leaky bucket algorithm to enforce rate limits. It maintains separate rate limiters for different keys (e.g., different IPs or users).
func (*UberRateLimiter) Allow ¶ added in v1.0.0
func (u *UberRateLimiter) Allow(key string, limit int, window time.Duration) (bool, int, time.Duration)
Allow checks if a request is allowed based on the key and rate limit configuration. It implements the common.RateLimiter interface using the leaky bucket algorithm.
Parameters:
- key: Unique identifier for the rate limit bucket (e.g., "api:IP:192.168.1.1")
- limit: Maximum number of requests allowed within the window
- window: Time duration for the rate limit window
Returns:
- allowed: true if the request is allowed, false if rate limit exceeded
- remaining: Estimated number of remaining requests in the current window
- reset: Duration until the next request will be allowed (0 if allowed now)
type UserAuthProvider ¶ added in v1.0.0
type UserAuthProvider[T any] interface { // AuthenticateUser authenticates a request and returns the user object if authentication is successful. // It examines the request for authentication credentials (such as headers, cookies, or query parameters) // and validates them according to the provider's implementation. // Returns the user object if the request is authenticated, nil and an error otherwise. AuthenticateUser(r *http.Request) (*T, error) }
UserAuthProvider defines an interface for authentication providers that return a user object. Different authentication mechanisms can implement this interface to be used with the AuthenticationWithUserProvider middleware.