feat: add CORS and rate limiting middleware
CORS: - Configurable allowed origins (wildcard "*" or specific domains) - Handles OPTIONS preflight with configurable methods, headers, max-age - Exposed headers support for browser API access - Env override: CORS_ALLOWED_ORIGINS Rate Limiting: - In-memory per-IP sliding window counter - Configurable request limit and time window - Background goroutine cleans up stale IP entries - HTTP 429 with Retry-After header when exceeded - Extracts real IP from X-Forwarded-For and X-Real-IP (proxy-aware) - Env overrides: RATE_LIMIT_REQUESTS, RATE_LIMIT_WINDOW, RATE_LIMIT_CLEANUP_INTERVAL - Set requests=0 in config to disable Both wired into main.go as middleware chain: rate_limit → cors → handler. Config example updated with [cors] and [rate_limit] sections. Full test coverage for both middleware packages.
This commit is contained in:
parent
4c54ed5b56
commit
ebeaeeef21
8 changed files with 616 additions and 6 deletions
|
|
@ -41,3 +41,23 @@ password = ""
|
|||
db = 0
|
||||
# Cache TTL for search results (env: VALKEY_CACHE_TTL)
|
||||
default_ttl = "5m"
|
||||
|
||||
[cors]
|
||||
# CORS configuration for browser-based clients.
|
||||
# Allowed origins: use "*" for all, or specific domains (env: CORS_ALLOWED_ORIGINS)
|
||||
allowed_origins = ["*"]
|
||||
# Allowed methods (default: GET, POST, OPTIONS)
|
||||
# allowed_methods = ["GET", "POST", "OPTIONS"]
|
||||
# Allowed headers (default: Content-Type, Authorization, X-Search-Token, X-Brave-Access-Token)
|
||||
# allowed_headers = ["Content-Type", "Authorization"]
|
||||
# Preflight cache duration in seconds (default: 3600)
|
||||
# max_age = 3600
|
||||
|
||||
[rate_limit]
|
||||
# Per-IP rate limiting. Set requests to 0 to disable.
|
||||
# Env: RATE_LIMIT_REQUESTS
|
||||
requests = 30
|
||||
# Time window for rate limit (env: RATE_LIMIT_WINDOW)
|
||||
window = "1m"
|
||||
# How often to clean up stale IP entries (env: RATE_LIMIT_CLEANUP_INTERVAL)
|
||||
cleanup_interval = "5m"
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue