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 is necessary because GORM's methods like Commit return *gorm.DB for chaining, which doesn't match the interface signature aiming for simple error returns.
func NewGormTransactionWrapper ¶ added in v1.1.5
func NewGormTransactionWrapper(tx *gorm.DB) *GormTransactionWrapper
NewGormTransactionWrapper creates a new wrapper around a GORM transaction.
func (*GormTransactionWrapper) Commit ¶ added in v1.1.5
func (w *GormTransactionWrapper) Commit() error
Commit implements the DatabaseTransaction interface.
func (*GormTransactionWrapper) GetDB ¶ added in v1.1.5
func (w *GormTransactionWrapper) GetDB() *gorm.DB
GetDB returns the underlying *gorm.DB instance.
func (*GormTransactionWrapper) Rollback ¶ added in v1.1.5
func (w *GormTransactionWrapper) Rollback() error
Rollback implements the DatabaseTransaction interface.
func (*GormTransactionWrapper) RollbackTo ¶ added in v1.1.5
func (w *GormTransactionWrapper) RollbackTo(name string) error
RollbackTo implements the DatabaseTransaction interface.
func (*GormTransactionWrapper) SavePoint ¶ added in v1.1.5
func (w *GormTransactionWrapper) SavePoint(name string) error
SavePoint implements the DatabaseTransaction interface.
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
func NewIDGenerator ¶ added in v1.1.2
func NewIDGenerator(bufferSize int) *IDGenerator
NewIDGenerator creates a new IDGenerator with the specified buffer size
func (*IDGenerator) GetID ¶ added in v1.1.2
func (g *IDGenerator) GetID() string
GetID returns a precomputed UUID from the channel. This is significantly more efficient than generating UUIDs on-demand since the generation happens in a background goroutine and is batched. The channel acts as a buffer, ensuring there's always a pool of IDs ready. This method will block if the channel is empty until a UUID becomes available.
func (*IDGenerator) GetIDNonBlocking ¶ added in v1.1.2
func (g *IDGenerator) GetIDNonBlocking() string
GetIDNonBlocking attempts to get a precomputed UUID from the channel without blocking. If the channel is empty (which should be rare with proper sizing), it will generate a new UUID on the spot rather than waiting. This ensures requests are never delayed even during extreme traffic spikes.
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 chains multiple middlewares together into a single middleware. The middlewares are applied in reverse order, so the first middleware in the list will be the outermost wrapper (the first to process the request and the last to process the response).
type UberRateLimiter ¶ added in v1.0.0
type UberRateLimiter struct {
// contains filtered or unexported fields
}
UberRateLimiter implements common.RateLimiter using Uber's ratelimit library (leaky bucket).
func NewUberRateLimiter ¶ added in v1.0.0
func NewUberRateLimiter() *UberRateLimiter
NewUberRateLimiter creates a new rate limiter using Uber's ratelimit library.
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.