pub struct RateLimitConfig {
pub max_requests: usize,
pub window_secs: Duration,
pub get_id: fn(req: &ServiceRequest) -> String,
pub on_exceed: fn(id: &String, config: &RateLimitConfig, req: &ServiceRequest) -> HttpResponse,
}Expand description
Configuration for rate limiting middleware.
This struct contains all the parameters needed to configure rate limiting behavior, including request limits, time windows, and callback functions for client identification and rate limit exceeded handling.
§Examples
use actix_web::HttpResponse;
use actix_web_ratelimit::config::RateLimitConfig;
// Basic configuration
let config = RateLimitConfig::default()
.max_requests(100)
.window_secs(3600);
// Advanced configuration with custom handlers
let config = RateLimitConfig::default()
.max_requests(10)
.window_secs(60)
.id(|req| {
// Custom client identification based on API key
req.headers()
.get("X-API-Key")
.and_then(|h| h.to_str().ok())
.unwrap_or("anonymous")
.to_string()
})
.exceeded(|id, _config, _req| {
// Custom rate limit exceeded response
HttpResponse::TooManyRequests()
.body(format!("Rate limit exceeded for client: {}", id))
});Fields§
§max_requests: usizeMaximum number of requests allowed within the time window
window_secs: DurationDuration of the sliding time window
get_id: fn(req: &ServiceRequest) -> StringFunction to extract client identifier from the request. Typically extracts IP address, but can be customized for API keys, user IDs, etc.
on_exceed: fn(id: &String, config: &RateLimitConfig, req: &ServiceRequest) -> HttpResponseFunction called when rate limit is exceeded. Receives the client ID, configuration, and request, returns the HTTP response.
Implementations§
Source§impl RateLimitConfig
impl RateLimitConfig
Sourcepub fn max_requests(self, value: usize) -> Self
pub fn max_requests(self, value: usize) -> Self
Sourcepub fn window_secs(self, value: u64) -> Self
pub fn window_secs(self, value: u64) -> Self
Sourcepub fn id(self, fn_id: fn(req: &ServiceRequest) -> String) -> Self
pub fn id(self, fn_id: fn(req: &ServiceRequest) -> String) -> Self
Sets a custom function to extract client identifier from requests.
By default, the middleware uses the client’s IP address as identifier. This method allows customization based on headers, authentication, etc.
§Arguments
fn_id- Function that takes aServiceRequestand returns a client identifier string
§Examples
use actix_web_ratelimit::config::RateLimitConfig;
// Rate limit by API key
let config = RateLimitConfig::default()
.id(|req| {
req.headers()
.get("X-API-Key")
.and_then(|h| h.to_str().ok())
.unwrap_or("anonymous")
.to_string()
});
// Rate limit by custom header
let config = RateLimitConfig::default()
.id(|req| {
// Extract user ID from custom header
req.headers()
.get("X-User-ID")
.and_then(|h| h.to_str().ok())
.unwrap_or("guest")
.to_string()
});Sourcepub fn exceeded(
self,
fn_exceed: fn(id: &String, config: &RateLimitConfig, req: &ServiceRequest) -> HttpResponse,
) -> Self
pub fn exceeded( self, fn_exceed: fn(id: &String, config: &RateLimitConfig, req: &ServiceRequest) -> HttpResponse, ) -> Self
Sets a custom function to handle rate limit exceeded scenarios.
By default, returns HTTP 429 with “Too many requests” message. This method allows customization of the response format, headers, etc.
§Arguments
fn_exceed- Function that takes client ID, config, and request, returns HTTP response
§Examples
use actix_web::HttpResponse;
use actix_web_ratelimit::config::RateLimitConfig;
// Custom error response with details
let config = RateLimitConfig::default()
.exceeded(|id, config, _req| {
HttpResponse::TooManyRequests()
.body(format!(
"Rate limit exceeded for client: {}. Limit: {} requests per {} seconds.",
id,
config.max_requests,
config.window_secs.as_secs()
))
});
// Custom headers and retry-after
let config = RateLimitConfig::default()
.exceeded(|_id, config, _req| {
HttpResponse::TooManyRequests()
.append_header(("Retry-After", config.window_secs.as_secs()))
.append_header(("X-RateLimit-Limit", config.max_requests))
.body("Rate limit exceeded. Please try again later.")
});Trait Implementations§
Source§impl Clone for RateLimitConfig
impl Clone for RateLimitConfig
Source§fn clone(&self) -> RateLimitConfig
fn clone(&self) -> RateLimitConfig
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read moreSource§impl Default for RateLimitConfig
impl Default for RateLimitConfig
Source§fn default() -> Self
fn default() -> Self
Creates a default rate limiting configuration.
§Default Values
max_requests: 10 requestswindow_secs: 100 secondsget_id: Extracts real IP address from connection infoon_exceed: Returns HTTP 429 “Too Many Requests” with plain text body
§Example
use actix_web_ratelimit::config::RateLimitConfig;
let config = RateLimitConfig::default();
assert_eq!(config.max_requests, 10);