2022-03-18 18:00:33 +01:00
|
|
|
# actix-limitation
|
|
|
|
|
|
|
|
> Rate limiter using a fixed window counter for arbitrary keys, backed by Redis for Actix Web.
|
|
|
|
> Originally based on <https://github.com/fnichol/limitation>.
|
|
|
|
|
|
|
|
[![crates.io](https://img.shields.io/crates/v/actix-limitation?label=latest)](https://crates.io/crates/actix-limitation)
|
2023-09-16 04:36:29 +02:00
|
|
|
[![Documentation](https://docs.rs/actix-limitation/badge.svg?version=0.5.1)](https://docs.rs/actix-limitation/0.5.1)
|
2022-03-18 18:00:33 +01:00
|
|
|
![Apache 2.0 or MIT licensed](https://img.shields.io/crates/l/actix-limitation)
|
2023-09-16 04:36:29 +02:00
|
|
|
[![Dependency Status](https://deps.rs/crate/actix-limitation/0.5.1/status.svg)](https://deps.rs/crate/actix-limitation/0.5.1)
|
2022-03-18 18:00:33 +01:00
|
|
|
|
|
|
|
## Examples
|
|
|
|
|
|
|
|
```toml
|
|
|
|
[dependencies]
|
|
|
|
actix-web = "4"
|
2023-09-16 04:29:58 +02:00
|
|
|
actix-limitation = "0.5"
|
2022-03-18 18:00:33 +01:00
|
|
|
```
|
|
|
|
|
|
|
|
```rust
|
|
|
|
use actix_limitation::{Limiter, RateLimiter};
|
2022-09-11 01:02:54 +02:00
|
|
|
use actix_session::SessionExt as _;
|
|
|
|
use actix_web::{dev::ServiceRequest, get, web, App, HttpServer, Responder};
|
|
|
|
use std::{sync::Arc, time::Duration};
|
2022-03-18 18:00:33 +01:00
|
|
|
|
|
|
|
#[get("/{id}/{name}")]
|
|
|
|
async fn index(info: web::Path<(u32, String)>) -> impl Responder {
|
|
|
|
format!("Hello {}! id:{}", info.1, info.0)
|
|
|
|
}
|
|
|
|
|
|
|
|
#[actix_web::main]
|
|
|
|
async fn main() -> std::io::Result<()> {
|
|
|
|
let limiter = web::Data::new(
|
2022-09-11 01:02:54 +02:00
|
|
|
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()))
|
|
|
|
})
|
2022-03-18 18:00:33 +01:00
|
|
|
.limit(5000)
|
|
|
|
.period(Duration::from_secs(3600)) // 60 minutes
|
2022-09-11 01:02:54 +02:00
|
|
|
.build()
|
|
|
|
.unwrap(),
|
2022-03-18 18:00:33 +01:00
|
|
|
);
|
|
|
|
HttpServer::new(move || {
|
|
|
|
App::new()
|
2022-09-11 01:02:54 +02:00
|
|
|
.wrap(RateLimiter::default())
|
2022-03-18 18:00:33 +01:00
|
|
|
.app_data(limiter.clone())
|
|
|
|
.service(index)
|
|
|
|
})
|
2022-09-11 01:02:54 +02:00
|
|
|
.bind(("127.0.0.1", 8080))?
|
2022-03-18 18:00:33 +01:00
|
|
|
.run()
|
|
|
|
.await
|
|
|
|
}
|
|
|
|
```
|