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.
88 lines
2.3 KiB
Go
88 lines
2.3 KiB
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
// CORSConfig controls Cross-Origin Resource Sharing headers.
|
|
type CORSConfig struct {
|
|
// AllowedOrigins is a list of allowed origin patterns.
|
|
// Use "*" to allow all origins, or specific domains like "https://example.com".
|
|
AllowedOrigins []string
|
|
// AllowedMethods defaults to GET, POST, OPTIONS if empty.
|
|
AllowedMethods []string
|
|
// AllowedHeaders defaults to Content-Type, Authorization if empty.
|
|
AllowedHeaders []string
|
|
// ExposedHeaders lists headers the browser can access from the response.
|
|
ExposedHeaders []string
|
|
// MaxAge is the preflight cache duration in seconds (default: 3600).
|
|
MaxAge int
|
|
}
|
|
|
|
// CORS returns a middleware that sets CORS headers on all responses
|
|
// and handles OPTIONS preflight requests.
|
|
func CORS(cfg CORSConfig) func(http.Handler) http.Handler {
|
|
origins := cfg.AllowedOrigins
|
|
if len(origins) == 0 {
|
|
origins = []string{"*"}
|
|
}
|
|
|
|
methods := cfg.AllowedMethods
|
|
if len(methods) == 0 {
|
|
methods = []string{"GET", "POST", "OPTIONS"}
|
|
}
|
|
|
|
headers := cfg.AllowedHeaders
|
|
if len(headers) == 0 {
|
|
headers = []string{"Content-Type", "Authorization", "X-Search-Token", "X-Brave-Access-Token"}
|
|
}
|
|
|
|
maxAge := cfg.MaxAge
|
|
if maxAge <= 0 {
|
|
maxAge = 3600
|
|
}
|
|
|
|
methodsStr := strings.Join(methods, ", ")
|
|
headersStr := strings.Join(headers, ", ")
|
|
exposedStr := strings.Join(cfg.ExposedHeaders, ", ")
|
|
maxAgeStr := strconv.Itoa(maxAge)
|
|
|
|
return func(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
origin := r.Header.Get("Origin")
|
|
|
|
// Determine the allowed origin for this request.
|
|
allowedOrigin := ""
|
|
for _, o := range origins {
|
|
if o == "*" {
|
|
allowedOrigin = "*"
|
|
break
|
|
}
|
|
if o == origin {
|
|
allowedOrigin = origin
|
|
break
|
|
}
|
|
}
|
|
|
|
if allowedOrigin != "" {
|
|
w.Header().Set("Access-Control-Allow-Origin", allowedOrigin)
|
|
w.Header().Set("Access-Control-Allow-Methods", methodsStr)
|
|
w.Header().Set("Access-Control-Allow-Headers", headersStr)
|
|
if exposedStr != "" {
|
|
w.Header().Set("Access-Control-Expose-Headers", exposedStr)
|
|
}
|
|
w.Header().Set("Access-Control-Max-Age", maxAgeStr)
|
|
}
|
|
|
|
// Handle preflight.
|
|
if r.Method == http.MethodOptions {
|
|
w.WriteHeader(http.StatusNoContent)
|
|
return
|
|
}
|
|
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
}
|