A super simple rate limiting middleware for the thruster web framework.
Currently supports only the hyper backend of thruster, basically hyper_server
feature must be enabled!
```rust
struct ServerState {
rate_limiter: RateLimiter
struct RequestState(RateLimiter
struct RateLimiterConf;
impl Configuration
async fn root(mut context: Ctx, next: MiddlewareNext
fn generatecontext(request: HyperRequest, state: &ServerState, _path: &str) -> Ctx { return Ctx::new( request, RequestState(state.ratelimiter.clone(), Box::new(RateLimiterConf)), ); }
async fn helloworld() { let ratelimiter = RateLimiter { max: 100, per_s: 60, store: MapStore::new(), };
let app = App::<HyperRequest, Ctx, ServerState>::create(generate_context, ServerState { rate_limiter })
.middleware("/", m![rate_limit_middleware])
.get("/", m![root])
.commit();
let response = Testable::get(&app, "/", vec![])
.await
.unwrap()
.expect_status(200, "OK");
assert_eq!(response.body_string(), BODY_STR);
} ```
```rust
pub struct RateLimiter
max
: maximum amount of requests allowed per_s
per_s
: when does max
resetstore
: anything that implements the Store
trait, 2 stores are provided by the libraryThis is currently pretty basic, but you can extend the functionality of the rate limiter based on your needs by implementing the Configuration
trait
```rust
pub trait Configuration) -> bool {
return true;
}
fn getkey(&self, context: &TypedHyperContext) -> String {
if let Some(request) = context.hyperrequest.asref() {
if let Some(ip) = request.ip {
return ip.to_string();
}
}
return "".to_string();
}
} ```
Simple in-memory store: ```rust
pub struct MapStore {
hash_map: Arc
Redis store: ```rust
pub struct RedisStore { connection_manager: ConnectionManager, } ```