Documentation
¶
Index ¶
- func AssertContains(slice []string, item string) bool
- func AssertEqual(expected, actual interface{}) bool
- func AssertSliceEqual(expected, actual []string) bool
- func CleanupRateLimiters()
- func GetRequestID(c *gin.Context) (string, bool)
- func GetRequestIDFromHeader(r *http.Request, header string) string
- func GetTokenExpiresAt(c *gin.Context) (time.Time, bool)
- func GetTokenID(c *gin.Context) (string, bool)
- func GetTokenIssuedAt(c *gin.Context) (time.Time, bool)
- func GetUserID(c *gin.Context) (string, bool)
- func GetUserIDOrAbort(c *gin.Context) (string, bool)
- func GetUserRoles(c *gin.Context) ([]string, bool)
- func IsTimeout(c *gin.Context) bool
- func SetRequestID(c *gin.Context, id string)
- func SetTokenExpiresAt(c *gin.Context, expiresAt time.Time)
- func SetTokenID(c *gin.Context, tokenID string)
- func SetTokenIssuedAt(c *gin.Context, issuedAt time.Time)
- func SetUserID(c *gin.Context, userID string)
- func SetUserRoles(c *gin.Context, roles []string)
- func TestContext(method, path string, headers map[string]string) (*gin.Context, *httptest.ResponseRecorder)
- func TestHandler(executed *[]string) gin.HandlerFunc
- type CORSConfig
- type Chain
- type Condition
- func And(conds ...Condition) Condition
- func ContentTypeIs(contentTypes ...string) Condition
- func Custom(fn func(*gin.Context) bool) Condition
- func HasPermission(service rbac.Service, resource, action string) Condition
- func HasRequestID() Condition
- func HasRolePermission(service rbac.Service, resource, action string) Condition
- func HasUserPermission(service rbac.Service, resource, action string) Condition
- func HeaderEquals(key, value string) Condition
- func HeaderExists(key string) Condition
- func IsAuthenticated() Condition
- func MethodIs(methods ...string) Condition
- func Not(cond Condition) Condition
- func OnTimeout() Condition
- func Or(conds ...Condition) Condition
- func PathHasPrefix(prefix string) Condition
- func PathHasSuffix(suffix string) Condition
- func PathIs(paths ...string) Condition
- func PathMatches(pattern string) Condition
- type ErrorHandler
- type MemoryLimiterStore
- type MemoryWindowCounterStore
- func (s *MemoryWindowCounterStore) Clear()
- func (s *MemoryWindowCounterStore) Close() error
- func (s *MemoryWindowCounterStore) Get(key string, window time.Time) (int64, error)
- func (s *MemoryWindowCounterStore) Increment(key string, window time.Time) (int64, error)
- func (s *MemoryWindowCounterStore) IncrementWithinLimit(key string, window time.Time, limit int64) (int64, bool, error)
- type Middleware
- func Auth(jwtService jwt.Service) Middleware
- func CORS(options ...Option[CORSConfig]) Middleware
- func CORSDefault() Middleware
- func Cache(cache shardedcache.CacheInterface) Middleware
- func CacheWithGroup(cache shardedcache.CacheInterface, groupName string) Middleware
- func Logger(options ...logger.Option) Middleware
- func RateLimit(rps, burst int, opts ...RateOption) Middleware
- func RateLimitPerDay(limit int, opts ...RateOption) Middleware
- func RateLimitPerHour(limit int, opts ...RateOption) Middleware
- func RateLimitPerMinute(limit int, opts ...RateOption) Middleware
- func Recovery(options ...logger.Option) Middleware
- func RecoveryWith(handler RecoveryHandler, loggerOptions ...logger.Option) Middleware
- func RequestID(opts ...RequestIDOption) Middleware
- func RequirePermission(service rbac.Service, resource, action string) Middleware
- func RequireRolePermission(service rbac.Service, resource, action string) Middleware
- func RequireUserPermission(service rbac.Service, resource, action string) Middleware
- func TestMiddleware(name string, executed *[]string) Middleware
- func Timeout(options ...Option[TimeoutConfig]) Middleware
- type Option
- func WithAllowCredentials(allow bool) Option[CORSConfig]
- func WithAllowHeaders(headers ...string) Option[CORSConfig]
- func WithAllowMethods(methods ...string) Option[CORSConfig]
- func WithAllowOrigins(origins ...string) Option[CORSConfig]
- func WithExposeHeaders(headers ...string) Option[CORSConfig]
- func WithMaxAge(maxAge time.Duration) Option[CORSConfig]
- func WithTimeout(timeout time.Duration) Option[TimeoutConfig]
- func WithTimeoutMessage(message string) Option[TimeoutConfig]
- func WithTimeoutResponse(response any) Option[TimeoutConfig]
- type RateLimitStore
- type RateOption
- func WithDynamicLimits(getLimits func(key string) (rps int, burst int)) RateOption
- func WithDynamicWindowLimits(getLimit func(key string) int) RateOption
- func WithIP() RateOption
- func WithKeyFunc(keyFunc func(*gin.Context) string) RateOption
- func WithPath() RateOption
- func WithSkipFunc(skipFunc func(*gin.Context) bool) RateOption
- func WithStore(store RateLimitStore) RateOption
- func WithUser() RateOption
- func WithWait(timeout time.Duration) RateOption
- func WithWindowStore(store WindowCounterStore) RateOption
- func WithoutRateLimitHeaders() RateOption
- func WithoutRetryAfterHeader() RateOption
- type RecoveryHandler
- type RequestIDConfig
- type RequestIDOption
- type TimeWindow
- type TimeoutConfig
- type WindowCounterStore
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AssertContains ¶
AssertContains checks if slice contains the specified element
func AssertEqual ¶
func AssertEqual(expected, actual interface{}) bool
AssertEqual checks if two values are equal
func AssertSliceEqual ¶
AssertSliceEqual checks if two string slices are equal
func CleanupRateLimiters ¶
func CleanupRateLimiters()
CleanupRateLimiters provides comprehensive cleanup of all rate limiter stores. It cleans up both token bucket stores and window counter stores, including default shared stores and all custom stores created with WithStore() or WithWindowStore().
Usage:
// At application shutdown
defer func() {
ginx.CleanupRateLimiters()
}()
This function is goroutine-safe and can be called multiple times safely.
func GetRequestID ¶
GetRequestID gets the request ID from the context
func GetRequestIDFromHeader ¶
Expose helper to fetch from standard header if needed (not used by middleware chain directly)
func GetTokenExpiresAt ¶
GetTokenExpiresAt gets the token expiration time from the context
func GetTokenID ¶
GetTokenID gets the token ID from the context
func GetTokenIssuedAt ¶
GetTokenIssuedAt gets the token issued time from the context
func GetUserIDOrAbort ¶
GetUserIDOrAbort gets user ID from context or aborts with 401
func GetUserRoles ¶
GetUserRoles gets the user roles from the context
func IsTimeout ¶
IsTimeout checks if the current request has timed out. Returns true if the request was terminated due to timeout.
func SetRequestID ¶
SetRequestID sets the request ID in the context
func SetTokenExpiresAt ¶
SetTokenExpiresAt sets the token expiration time in the context
func SetTokenID ¶
SetTokenID sets the token ID in the context
func SetTokenIssuedAt ¶
SetTokenIssuedAt sets the token issued time in the context
func SetUserRoles ¶
SetUserRoles sets the user roles in the context
func TestContext ¶
func TestContext(method, path string, headers map[string]string) (*gin.Context, *httptest.ResponseRecorder)
TestContext creates a gin.Context for testing
func TestHandler ¶
func TestHandler(executed *[]string) gin.HandlerFunc
TestHandler creates a handler for testing
Types ¶
type CORSConfig ¶
type CORSConfig struct {
AllowOrigins []string // Allowed origins, defaults to same-origin
AllowMethods []string // Allowed methods, defaults to GET, POST, PUT, DELETE, OPTIONS
AllowHeaders []string // Allowed request headers, defaults to common headers
ExposeHeaders []string // Headers exposed to the client
AllowCredentials bool // Whether to allow credentials, defaults to false
MaxAge time.Duration // Preflight request cache duration, defaults to 12 hours
}
CORSConfig CORS configuration structure
type Chain ¶
type Chain struct {
// contains filtered or unexported fields
}
Chain is a middleware chain builder for Gin
func (*Chain) Build ¶
func (c *Chain) Build() gin.HandlerFunc
Build builds the final gin.HandlerFunc
func (*Chain) OnError ¶
func (c *Chain) OnError(handler ErrorHandler) *Chain
OnError sets the error handler for the chain
type Condition ¶
Condition represents a condition function that determines whether a middleware should be executed.
func ContentTypeIs ¶
ContentTypeIs checks if the Content-Type matches any of the specified types Uses precise MIME type parsing to avoid false positives
func HasPermission ¶
HasPermission checks combined role and direct user permissions
func HasRequestID ¶
func HasRequestID() Condition
Convenience condition: HasRequestID checks presence of request id in context
func HasRolePermission ¶
HasRolePermission checks role based permissions only
func HasUserPermission ¶
HasUserPermission checks direct user permissions only
func HeaderEquals ¶
HeaderEquals checks if the request header value matches
func HeaderExists ¶
HeaderExists checks if the request header exists
func IsAuthenticated ¶
func IsAuthenticated() Condition
IsAuthenticated checks if the user is authenticated
func PathHasPrefix ¶
PathHasPrefix checks if the path has the specified prefix
func PathHasSuffix ¶
PathHasSuffix checks if the path has the specified suffix
func PathMatches ¶
PathMatches checks if the path matches the specified regex pattern
type ErrorHandler ¶
ErrorHandler represents an error handler function type.
type MemoryLimiterStore ¶
type MemoryLimiterStore struct {
// contains filtered or unexported fields
}
MemoryLimiterStore provides a thread-safe, in-memory implementation of RateLimitStore. It automatically cleans up expired limiters to prevent memory leaks and is registered globally for automatic resource management.
func (*MemoryLimiterStore) Clear ¶
func (s *MemoryLimiterStore) Clear()
Clear removes all stored rate limiters and access time records.
func (*MemoryLimiterStore) Close ¶
func (s *MemoryLimiterStore) Close() error
Close stops the cleanup goroutine and releases resources.
func (*MemoryLimiterStore) Delete ¶
func (s *MemoryLimiterStore) Delete(key string)
Delete removes a rate limiter and its access time record.
type MemoryWindowCounterStore ¶
type MemoryWindowCounterStore struct {
// contains filtered or unexported fields
}
MemoryWindowCounterStore provides a thread-safe, in-memory implementation of WindowCounterStore. It uses a fixed window algorithm for time-based rate limiting (minute/hour/day).
func (*MemoryWindowCounterStore) Clear ¶
func (s *MemoryWindowCounterStore) Clear()
Clear removes all stored counters and access time records.
func (*MemoryWindowCounterStore) Close ¶
func (s *MemoryWindowCounterStore) Close() error
Close stops the cleanup goroutine and releases resources.
func (*MemoryWindowCounterStore) Increment ¶
Increment increments the counter for the given key and window, returns new count
func (*MemoryWindowCounterStore) IncrementWithinLimit ¶
func (s *MemoryWindowCounterStore) IncrementWithinLimit(key string, window time.Time, limit int64) (int64, bool, error)
IncrementWithinLimit atomically increments the current window counter when under limit.
type Middleware ¶
type Middleware func(gin.HandlerFunc) gin.HandlerFunc
Middleware represents a middleware function that takes a HandlerFunc and returns a new HandlerFunc.
func CORS ¶
func CORS(options ...Option[CORSConfig]) Middleware
CORS creates a CORS middleware (requires explicit origin configuration)
func CORSDefault ¶
func CORSDefault() Middleware
CORSDefault creates a default CORS middleware (for development only)
func Cache ¶
func Cache(cache shardedcache.CacheInterface) Middleware
Cache creates a cache middleware using the default cache group
func CacheWithGroup ¶
func CacheWithGroup(cache shardedcache.CacheInterface, groupName string) Middleware
CacheWithGroup creates a cache middleware using the specified cache group
func Logger ¶
func Logger(options ...logger.Option) Middleware
Logger create a logging middleware with the given options.
func RateLimit ¶
func RateLimit(rps, burst int, opts ...RateOption) Middleware
RateLimit creates a rate limiting middleware with the specified limits and options. This is the recommended way to configure rate limiting with maximum flexibility.
Resource Management: All stores (both default shared and custom stores) are automatically managed. Use CleanupRateLimiters() at application shutdown for comprehensive cleanup.
Parameters:
- rps: Maximum requests per second allowed
- burst: Maximum burst size (tokens that can be consumed immediately)
- opts: Optional configuration functions
Examples:
// Basic rate limiting (uses shared global store) r.Use(ginx.RateLimit(100, 200)) // Rate limiting by authenticated user (uses shared store) r.Use(ginx.RateLimit(50, 100, ginx.WithUser())) // Custom store (automatically managed) store := ginx.NewMemoryLimiterStore(10 * time.Minute) r.Use(ginx.RateLimit(10, 20, ginx.WithStore(store))) // Cleanup at shutdown: ginx.CleanupRateLimiters() // Skip rate limiting for admin users r.Use(ginx.RateLimit(100, 200, ginx.WithSkipFunc(isAdminUser)))
func RateLimitPerDay ¶
func RateLimitPerDay(limit int, opts ...RateOption) Middleware
RateLimitPerDay creates a rate limiting middleware that limits requests per day. Uses a fixed window algorithm (window resets at midnight).
Parameters:
- limit: Maximum requests allowed per day (resets at midnight)
- opts: Optional configuration functions (WithUser, WithPath, etc.)
Examples:
// Limit to 10000 requests per day r.Use(ginx.RateLimitPerDay(10000)) // Per-user limit of 5000 requests per day r.Use(ginx.RateLimitPerDay(5000, ginx.WithUser()))
func RateLimitPerHour ¶
func RateLimitPerHour(limit int, opts ...RateOption) Middleware
RateLimitPerHour creates a rate limiting middleware that limits requests per hour. Uses a fixed window algorithm (window resets at 0 minutes of each hour).
Parameters:
- limit: Maximum requests allowed per hour
- opts: Optional configuration functions (WithUser, WithPath, etc.)
Examples:
// Limit to 1000 requests per hour r.Use(ginx.RateLimitPerHour(1000)) // Per-user limit of 500 requests per hour r.Use(ginx.RateLimitPerHour(500, ginx.WithUser()))
func RateLimitPerMinute ¶
func RateLimitPerMinute(limit int, opts ...RateOption) Middleware
RateLimitPerMinute creates a rate limiting middleware that limits requests per minute. Uses a fixed window algorithm (window resets at 0 seconds of each minute).
Parameters:
- limit: Maximum requests allowed per minute
- opts: Optional configuration functions (WithUser, WithPath, etc.)
Examples:
// Limit to 60 requests per minute r.Use(ginx.RateLimitPerMinute(60)) // Per-user limit of 100 requests per minute r.Use(ginx.RateLimitPerMinute(100, ginx.WithUser()))
func Recovery ¶
func Recovery(options ...logger.Option) Middleware
Recovery creates a panic recovery middleware.
func RecoveryWith ¶
func RecoveryWith(handler RecoveryHandler, loggerOptions ...logger.Option) Middleware
RecoveryWith creates a panic recovery middleware with a custom handler.
func RequestID ¶
func RequestID(opts ...RequestIDOption) Middleware
RequestID provides a simple request ID middleware. Behavior: - Read ID from Header (default: X-Request-ID) if present and RespectIncoming=true - Otherwise generate a new ID using crypto/rand (16 bytes -> 32 hex chars) - Store into gin context via SetRequestID and echo back in response header
func RequirePermission ¶
func RequirePermission(service rbac.Service, resource, action string) Middleware
RequirePermission based on roles and direct user permission checking middleware
func RequireRolePermission ¶
func RequireRolePermission(service rbac.Service, resource, action string) Middleware
RequireRolePermission based on role based permission only checking middleware
func RequireUserPermission ¶
func RequireUserPermission(service rbac.Service, resource, action string) Middleware
RequireUserPermission based on direct user permission only checking middleware
func TestMiddleware ¶
func TestMiddleware(name string, executed *[]string) Middleware
TestMiddleware creates middleware for testing that records execution state
func Timeout ¶
func Timeout(options ...Option[TimeoutConfig]) Middleware
Timeout middleware to set a timeout for requests. This version uses a serial approach to avoid race conditions when accessing headers.
type Option ¶
type Option[T any] func(*T)
Option represents a generic option function for configuring various structures.
func WithAllowCredentials ¶
func WithAllowCredentials(allow bool) Option[CORSConfig]
WithAllowCredentials sets whether to allow credentials
func WithAllowHeaders ¶
func WithAllowHeaders(headers ...string) Option[CORSConfig]
WithAllowHeaders sets the allowed request headers
func WithAllowMethods ¶
func WithAllowMethods(methods ...string) Option[CORSConfig]
WithAllowMethods sets the allowed methods
func WithAllowOrigins ¶
func WithAllowOrigins(origins ...string) Option[CORSConfig]
WithAllowOrigins sets the allowed origins
func WithExposeHeaders ¶
func WithExposeHeaders(headers ...string) Option[CORSConfig]
WithExposeHeaders sets the exposed response headers
func WithMaxAge ¶
func WithMaxAge(maxAge time.Duration) Option[CORSConfig]
WithMaxAge sets the preflight request cache duration
func WithTimeout ¶
func WithTimeout(timeout time.Duration) Option[TimeoutConfig]
WithTimeout sets timeout duration
func WithTimeoutMessage ¶
func WithTimeoutMessage(message string) Option[TimeoutConfig]
WithTimeoutMessage sets timeout message
func WithTimeoutResponse ¶
func WithTimeoutResponse(response any) Option[TimeoutConfig]
WithTimeoutResponse sets timeout response content
type RateLimitStore ¶
type RateLimitStore interface {
// Get returns the limiter for the given key
Get(key string) (*rate.Limiter, bool)
// Set stores the limiter for the given key
Set(key string, limiter *rate.Limiter)
// Delete removes the limiter for the given key
Delete(key string)
// Clear removes all expired limiters
Clear()
// Close cleans up resources
Close() error
}
RateLimitStore defines the interface for storing and managing rate limiters. It provides methods to store, retrieve, and manage rate.Limiter instances by key.
func NewMemoryLimiterStore ¶
func NewMemoryLimiterStore(maxIdle time.Duration) RateLimitStore
NewMemoryLimiterStore creates a thread-safe in-memory store with automatic cleanup.
Parameters:
- maxIdle: Duration to keep unused limiters (defaults to 5 minutes if <= 0)
Resource Management: The store is automatically registered globally and cleaned up by CleanupRateLimiters(). Manual Close() is optional unless immediate cleanup is needed.
type RateOption ¶
type RateOption func(*rateLimiter)
RateOption configures the rate limiter behavior. Options provide a flexible way to customize rate limiting without exposing complex configuration methods.
func WithDynamicLimits ¶
func WithDynamicLimits(getLimits func(key string) (rps int, burst int)) RateOption
WithDynamicLimits configures dynamic rate limiting where different keys can have different limits determined at runtime by the provided function. The function receives a key and should return (rps, burst) for that key. Note: When using this option, the rps and burst parameters to RateLimit are ignored as they will be determined dynamically. This option only works with RateLimit (token bucket), not with time-window rate limiting.
func WithDynamicWindowLimits ¶
func WithDynamicWindowLimits(getLimit func(key string) int) RateOption
WithDynamicWindowLimits configures dynamic time-window rate limiting where different keys can have different limits determined at runtime by the provided function. The function receives a key and should return the limit for that key. Note: When using this option, the limit parameter to RateLimitPerMinute/Hour/Day is ignored as it will be determined dynamically. This option only works with RateLimitPerMinute/Hour/Day, not with RateLimit (token bucket).
Example:
r.Use(ginx.RateLimitPerHour(0, // Base limit ignored when using dynamic limits
ginx.WithUser(),
ginx.WithDynamicWindowLimits(func(key string) int {
if strings.Contains(key, "user:premium_") {
return 100000 // Premium: 100k per hour
}
if strings.Contains(key, "user:pro_") {
return 10000 // Pro: 10k per hour
}
return 1000 // Free: 1k per hour
})))
func WithIP ¶
func WithIP() RateOption
WithIP configures rate limiting by client IP address. Each IP gets its own rate limit bucket. Note: This is the default behavior, so this option is typically redundant.
func WithKeyFunc ¶
func WithKeyFunc(keyFunc func(*gin.Context) string) RateOption
WithKeyFunc configures a custom key generation function. The key function determines how requests are grouped for rate limiting.
func WithPath ¶
func WithPath() RateOption
WithPath configures rate limiting by IP and path combination. This allows different rate limits for different endpoints per client.
func WithSkipFunc ¶
func WithSkipFunc(skipFunc func(*gin.Context) bool) RateOption
WithSkipFunc configures a function to skip rate limiting for certain requests. Useful for exempting admin users, health checks, etc.
func WithStore ¶
func WithStore(store RateLimitStore) RateOption
WithStore configures a custom storage backend for rate limiters. This allows distributed rate limiting using Redis or other systems.
Resource Management: Custom stores are automatically registered and will be cleaned up when CleanupRateLimiters() is called. Manual cleanup is optional but can be done by calling store.Close() directly if needed.
Example:
store := NewMemoryLimiterStore(10 * time.Minute) r.Use(ginx.RateLimit(100, 200, ginx.WithStore(store))) // Automatic cleanup at shutdown: ginx.CleanupRateLimiters()
func WithUser ¶
func WithUser() RateOption
WithUser configures rate limiting by authenticated user ID. Falls back to IP-based limiting if no user ID is found. Users are identified by 'user_id' in the Gin context (set by auth middleware) or X-User-ID header.
func WithWait ¶
func WithWait(timeout time.Duration) RateOption
WithWait configures the rate limiter to wait for available tokens instead of immediately rejecting requests. If the wait time exceeds the timeout, the request is rejected with a 429 status.
func WithWindowStore ¶
func WithWindowStore(store WindowCounterStore) RateOption
WithWindowStore configures a custom storage backend for window-based rate limiters. This is used for per-minute, per-hour, and per-day rate limiting.
Resource Management: Custom window stores are automatically registered and will be cleaned up when CleanupRateLimiters() is called.
Example:
store := NewMemoryWindowCounterStore(25 * time.Hour) r.Use(ginx.RateLimitPerHour(1000, ginx.WithWindowStore(store))) // Automatic cleanup at shutdown: ginx.CleanupRateLimiters()
func WithoutRateLimitHeaders ¶
func WithoutRateLimitHeaders() RateOption
WithoutRateLimitHeaders disables X-RateLimit-* headers in responses. By default, X-RateLimit-Limit, X-RateLimit-Remaining, and X-RateLimit-Reset headers are included. This does NOT affect Retry-After headers.
func WithoutRetryAfterHeader ¶
func WithoutRetryAfterHeader() RateOption
WithoutRetryAfterHeader disables Retry-After header in 429 responses. By default, Retry-After header is included in rate-limited responses as recommended by RFC 7231. Use this option only if you need to completely disable retry guidance for clients.
type RecoveryHandler ¶
type RequestIDConfig ¶
type RequestIDConfig struct {
// Header is the request/response header name to carry the ID
// Common choices: "X-Request-ID" (default) or "Traceparent" in W3C Trace Context
Header string
// Generator generates a new ID when the incoming request doesn't have one
Generator func() string
// RespectIncoming controls whether to trust and reuse the incoming header value
// If false, always override with a new ID
RespectIncoming bool
}
RequestIDConfig holds configuration for the RequestID middleware
type RequestIDOption ¶
type RequestIDOption = Option[RequestIDConfig]
RequestID options
func WithIgnoreIncoming ¶
func WithIgnoreIncoming() RequestIDOption
WithIgnoreIncoming disables using incoming header value; always generate a new ID
func WithRequestIDGenerator ¶
func WithRequestIDGenerator(gen func() string) RequestIDOption
WithRequestIDGenerator sets a custom ID generator
func WithRequestIDHeader ¶
func WithRequestIDHeader(header string) RequestIDOption
WithRequestIDHeader sets the header name (default: X-Request-ID)
type TimeWindow ¶
type TimeWindow int
TimeWindow represents different time window types for rate limiting
const ( TimeWindowSecond TimeWindow = iota // Per second (default token bucket) TimeWindowMinute // Per minute (sliding window) TimeWindowHour // Per hour (sliding window) TimeWindowDay // Per day (sliding window) )
type TimeoutConfig ¶
type TimeoutConfig struct {
Timeout time.Duration `json:"timeout"` // Timeout duration
Response any `json:"response"` // Timeout response content
}
TimeoutConfig timeout middleware configuration
type WindowCounterStore ¶
type WindowCounterStore interface {
// Increment increments the counter for the given key and window, returns new count
Increment(key string, window time.Time) (int64, error)
// IncrementWithinLimit atomically increments the counter when under limit.
// It returns the resulting count, whether the increment happened, and any errors.
IncrementWithinLimit(key string, window time.Time, limit int64) (count int64, allowed bool, err error)
// Get returns the current count for the given key and window
Get(key string, window time.Time) (int64, error)
// Clear removes expired counters
Clear()
// Close cleans up resources
Close() error
}
WindowCounterStore defines the interface for storing time-window based counters. Used for minute/hour/day rate limiting with fixed window algorithm.
func NewMemoryWindowCounterStore ¶
func NewMemoryWindowCounterStore(maxIdle time.Duration) WindowCounterStore
NewMemoryWindowCounterStore creates a thread-safe in-memory window counter store with automatic cleanup.
Parameters:
- maxIdle: Duration to keep unused counters (defaults to 25 hours if <= 0, sufficient for daily limits)
Resource Management: The store is automatically registered globally and cleaned up by CleanupRateLimiters().
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
auth_rbac
command
|
|
|
cache
command
|
|
|
ratelimit
command
|
|
|
ratelimit_combined
command
|
|
|
requestid
command
|
|
|
timeout
command
|
|
|
timeout_logging
command
|