Documentation
¶
Overview ¶
Package middleware provides HTTP middleware including response caching, rate limiting, and compression for the gateway.
Index ¶
- type CacheStats
- type CacheStore
- type CachedResponse
- type CachingConfig
- type CompressionConfig
- type CompressionMiddleware
- type DistributedRateLimiter
- type InMemoryCacheStore
- type InMemoryRateLimitStore
- type Logger
- type RateLimitConfig
- type RateLimitStore
- type RateLimiter
- func (rl *RateLimiter) Allow(r *http.Request) bool
- func (rl *RateLimiter) AllowForKey(key string) bool
- func (rl *RateLimiter) AllowWithConfig(r *http.Request, config *RateLimitConfig) bool
- func (rl *RateLimiter) BucketCount() int
- func (rl *RateLimiter) Cleanup(maxAge time.Duration)
- func (rl *RateLimiter) Config() RateLimitConfig
- type ResponseCache
- func (rc *ResponseCache) Get(r *http.Request, route *Route) *CachedResponse
- func (rc *ResponseCache) Invalidate(ctx context.Context, method, path string) error
- func (rc *ResponseCache) Set(r *http.Request, route *Route, statusCode int, headers http.Header, ...)
- func (rc *ResponseCache) Stats() *CacheStats
- func (rc *ResponseCache) WriteCachedResponse(w http.ResponseWriter, cached *CachedResponse)
- type Route
- type RouteCacheConfig
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type CacheStats ¶
type CacheStats struct {
// contains filtered or unexported fields
}
CacheStats tracks cache hit/miss metrics.
func (*CacheStats) Misses ¶
func (cs *CacheStats) Misses() int64
Misses returns the total cache misses.
type CacheStore ¶
type CacheStore interface {
Get(ctx context.Context, key string) ([]byte, error)
Set(ctx context.Context, key string, value []byte, ttl time.Duration) error
Delete(ctx context.Context, key string) error
}
CacheStore is the interface for a cache backend. This decouples from the concrete cache extension, allowing the gateway to use any backend that implements this interface.
type CachedResponse ¶
type CachedResponse struct {
StatusCode int `json:"statusCode"`
Headers map[string]string `json:"headers"`
Body []byte `json:"body"`
CachedAt time.Time `json:"cachedAt"`
TTL time.Duration `json:"ttl"`
}
CachedResponse represents a cached HTTP response.
type CachingConfig ¶
type CachingConfig struct {
Enabled bool `json:"enabled" yaml:"enabled"`
DefaultTTL time.Duration `json:"defaultTtl" yaml:"default_ttl"`
MaxSize int `json:"maxSize" yaml:"max_size"`
Methods []string `json:"methods,omitempty" yaml:"methods"`
VaryBy []string `json:"varyBy,omitempty" yaml:"vary_by"`
}
CachingConfig holds response caching settings.
type CompressionConfig ¶
type CompressionConfig struct {
// Enabled enables response compression.
Enabled bool `json:"enabled" yaml:"enabled"`
// MinSize is the minimum response body size (bytes) to trigger compression.
MinSize int `json:"minSize" yaml:"min_size"`
// Level is the gzip compression level (1-9, or -1 for default).
Level int `json:"level" yaml:"level"`
// ContentTypes lists MIME types eligible for compression.
// Empty means all compressible types.
ContentTypes []string `json:"contentTypes,omitempty" yaml:"content_types"`
}
CompressionConfig configures response compression.
type CompressionMiddleware ¶
type CompressionMiddleware struct {
// contains filtered or unexported fields
}
CompressionMiddleware wraps an http.Handler with gzip compression.
func NewCompressionMiddleware ¶
func NewCompressionMiddleware(config CompressionConfig) *CompressionMiddleware
NewCompressionMiddleware creates a new compression middleware.
type DistributedRateLimiter ¶
type DistributedRateLimiter struct {
*RateLimiter
// contains filtered or unexported fields
}
DistributedRateLimiter extends the basic RateLimiter with an external store for multi-instance rate limiting.
func NewDistributedRateLimiter ¶
func NewDistributedRateLimiter(config RateLimitConfig, store RateLimitStore) *DistributedRateLimiter
NewDistributedRateLimiter creates a rate limiter backed by an external store. Falls back to local token bucket if the store is unavailable.
func (*DistributedRateLimiter) AllowDistributed ¶
func (drl *DistributedRateLimiter) AllowDistributed(ctx context.Context, key string) bool
AllowDistributed checks the rate limit using the distributed store. Falls back to local limiter on store error.
type InMemoryCacheStore ¶
type InMemoryCacheStore struct {
// contains filtered or unexported fields
}
InMemoryCacheStore provides a simple in-memory LRU cache for the gateway. It is used as the default cache backend when no external store is configured.
func NewInMemoryCacheStore ¶
func NewInMemoryCacheStore(maxSize int) *InMemoryCacheStore
NewInMemoryCacheStore creates a new in-memory cache store.
func (*InMemoryCacheStore) CleanExpired ¶
func (s *InMemoryCacheStore) CleanExpired()
CleanExpired removes all expired entries.
func (*InMemoryCacheStore) Delete ¶
func (s *InMemoryCacheStore) Delete(_ context.Context, key string) error
type InMemoryRateLimitStore ¶
type InMemoryRateLimitStore struct {
// contains filtered or unexported fields
}
InMemoryRateLimitStore is a local implementation of RateLimitStore using sliding window counters. Useful for testing or single-instance deployments.
func NewInMemoryRateLimitStore ¶
func NewInMemoryRateLimitStore() *InMemoryRateLimitStore
NewInMemoryRateLimitStore creates a new in-memory rate limit store.
type Logger ¶
Logger is a minimal logging interface used by middleware. It mirrors the subset of forge.Logger that caching needs, avoiding a direct import of the root bastion package.
type RateLimitConfig ¶
type RateLimitConfig struct {
Enabled bool `json:"enabled" yaml:"enabled"`
RequestsPerSec float64 `json:"requestsPerSec" yaml:"requests_per_sec"`
Burst int `json:"burst" yaml:"burst"`
PerClient bool `json:"perClient" yaml:"per_client"`
KeyHeader string `json:"keyHeader,omitempty" yaml:"key_header"`
}
RateLimitConfig holds rate limiting settings.
type RateLimitStore ¶
type RateLimitStore interface {
// Allow checks if a request identified by key is allowed under the given
// rate limit. Returns true if allowed, false if rate-limited.
// The implementation should atomically increment the counter.
Allow(ctx context.Context, key string, limit float64, burst int, window time.Duration) (bool, error)
}
RateLimitStore is the interface for distributed rate limiting backends. Implementations must be safe for concurrent use.
type RateLimiter ¶
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter implements token-bucket rate limiting.
func NewRateLimiter ¶
func NewRateLimiter(config RateLimitConfig) *RateLimiter
NewRateLimiter creates a new rate limiter.
func (*RateLimiter) Allow ¶
func (rl *RateLimiter) Allow(r *http.Request) bool
Allow checks if a request is allowed.
func (*RateLimiter) AllowForKey ¶
func (rl *RateLimiter) AllowForKey(key string) bool
AllowForKey checks rate limit for the given key.
func (*RateLimiter) AllowWithConfig ¶
func (rl *RateLimiter) AllowWithConfig(r *http.Request, config *RateLimitConfig) bool
AllowWithConfig checks rate limit with a per-route override.
func (*RateLimiter) BucketCount ¶
func (rl *RateLimiter) BucketCount() int
BucketCount returns the number of active per-client buckets. This is primarily useful for testing cleanup behavior.
func (*RateLimiter) Cleanup ¶
func (rl *RateLimiter) Cleanup(maxAge time.Duration)
Cleanup removes stale buckets older than the given duration.
func (*RateLimiter) Config ¶
func (rl *RateLimiter) Config() RateLimitConfig
Config returns the rate limiter's configuration.
type ResponseCache ¶
type ResponseCache struct {
// contains filtered or unexported fields
}
ResponseCache provides HTTP response caching for the gateway. It supports:
- Configurable cache backends (in-memory, external via CacheStore interface)
- Per-route cache policies with TTL, vary-by headers, and method filtering
- Cache-Control header respect (no-cache, no-store, max-age)
- Automatic cache key generation based on method, path, query, and vary-by headers
- Cache invalidation via admin API
- Metrics (hits/misses)
func NewResponseCache ¶
func NewResponseCache(config CachingConfig, logger Logger, store CacheStore) *ResponseCache
NewResponseCache creates a new response cache.
func (*ResponseCache) Get ¶
func (rc *ResponseCache) Get(r *http.Request, route *Route) *CachedResponse
Get attempts to retrieve a cached response for the given request. Returns nil if not cached, cache is disabled, or the request is not cacheable.
func (*ResponseCache) Invalidate ¶
func (rc *ResponseCache) Invalidate(ctx context.Context, method, path string) error
Invalidate removes a cached entry for the given request.
func (*ResponseCache) Set ¶
func (rc *ResponseCache) Set(r *http.Request, route *Route, statusCode int, headers http.Header, body []byte)
Set stores a response in the cache.
func (*ResponseCache) Stats ¶
func (rc *ResponseCache) Stats() *CacheStats
Stats returns the cache statistics.
func (*ResponseCache) WriteCachedResponse ¶
func (rc *ResponseCache) WriteCachedResponse(w http.ResponseWriter, cached *CachedResponse)
WriteCachedResponse writes a cached response to the client.
type Route ¶
type Route struct {
Path string
Cache *RouteCacheConfig
Methods []string
}
Route is the minimal route representation needed by the cache middleware. The full Route type lives in the root bastion package.