mirror of
https://github.com/actix/actix-extras.git
synced 2025-06-26 10:27:42 +02:00
Limitation: custom key from closure (#281)
Co-authored-by: Rob Ede <robjtede@icloud.com>
This commit is contained in:
@ -17,9 +17,10 @@ actix-limitation = "0.3"
|
||||
```
|
||||
|
||||
```rust
|
||||
use std::time::Duration;
|
||||
use actix_web::{get, web, App, HttpServer, Responder};
|
||||
use actix_limitation::{Limiter, RateLimiter};
|
||||
use actix_session::SessionExt as _;
|
||||
use actix_web::{dev::ServiceRequest, get, web, App, HttpServer, Responder};
|
||||
use std::{sync::Arc, time::Duration};
|
||||
|
||||
#[get("/{id}/{name}")]
|
||||
async fn index(info: web::Path<(u32, String)>) -> impl Responder {
|
||||
@ -29,22 +30,24 @@ async fn index(info: web::Path<(u32, String)>) -> impl Responder {
|
||||
#[actix_web::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
let limiter = web::Data::new(
|
||||
Limiter::build("redis://127.0.0.1")
|
||||
.cookie_name("session-id".to_owned())
|
||||
.session_key("rate-api-id".to_owned())
|
||||
Limiter::builder("redis://127.0.0.1")
|
||||
.key_by(|req: &ServiceRequest| {
|
||||
req.get_session()
|
||||
.get(&"session-id")
|
||||
.unwrap_or_else(|_| req.cookie(&"rate-api-id").map(|c| c.to_string()))
|
||||
})
|
||||
.limit(5000)
|
||||
.period(Duration::from_secs(3600)) // 60 minutes
|
||||
.finish()
|
||||
.expect("Can't build actix-limiter"),
|
||||
.build()
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
HttpServer::new(move || {
|
||||
App::new()
|
||||
.wrap(RateLimiter)
|
||||
.wrap(RateLimiter::default())
|
||||
.app_data(limiter.clone())
|
||||
.service(index)
|
||||
})
|
||||
.bind("127.0.0.1:8080")?
|
||||
.bind(("127.0.0.1", 8080))?
|
||||
.run()
|
||||
.await
|
||||
}
|
||||
|
Reference in New Issue
Block a user