c3d9fbd8d3
Implementa fase 2 del issue 0016: - rate_limit_middleware: limita por IP (X-Forwarded-For > X-Real-IP > RemoteAddr) - rate_limiter_by_key: middleware configurable con keyFunc custom (API key, user ID...) - Cuando se rechaza responde 429 con HTTPError JSON y headers Retry-After + X-RateLimit-* - Tests con httptest.NewRecorder cubriendo: limite, burst, IPs independientes, XFF prioritario, recarga temporal, JSON body, headers IETF, GC stop idempotente, key vacia salta limit
2.2 KiB
2.2 KiB
name, kind, lang, domain, version, purity, signature, description, tags, uses_functions, uses_types, returns, returns_optional, error_type, imports, params, output, tested, tests, test_file_path, file_path
| name | kind | lang | domain | version | purity | signature | description | tags | uses_functions | uses_types | returns | returns_optional | error_type | imports | params | output | tested | tests | test_file_path | file_path | |||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| rate_limiter_by_key | function | go | infra | 1.0.0 | impure | func RateLimiterByKey(rl *RateLimiter, keyFunc func(r *http.Request) string) Middleware | Middleware HTTP configurable que aplica rate limiting con un extractor de clave custom. Permite limitar por API key, user ID, header arbitrario, etc. Si keyFunc devuelve cadena vacia el request pasa sin limit. |
|
|
|
|
false | error_go_core |
|
|
Middleware que aplica rate limit segun keyFunc, responde 429 con HTTPError JSON al exceder | true |
|
functions/infra/rate_limiter_by_key_test.go | functions/infra/rate_limiter_by_key.go |
Ejemplo
// Limit por API key
rl := RateLimiterNew(100, 200)
mw := RateLimiterByKey(rl, func(r *http.Request) string {
return r.Header.Get("X-API-Key")
})
// Limit por user ID extraido del JWT (suponiendo middleware previo que lo setea)
mwUser := RateLimiterByKey(rl, func(r *http.Request) string {
return r.Context().Value("user_id").(string)
})
Notas
Funcion impura — el middleware muta el estado del limiter. Reutiliza RateLimiterCheck, RateLimitHeaders y HTTPErrorResponse del registry. Si el keyFunc devuelve "" se interpreta como "sin clave identificable" y se deja pasar el request: util para endpoints publicos donde solo se quiere limitar requests autenticados. La respuesta 429 sigue el formato JSON estandar {"status":429,"code":"rate_limited","message":"too many requests"}.