rate limit an endpoint in rocket in rust

main.rs
#[macro_use] extern crate rocket;

use rocket::tokio::time::{self, Duration};
use rocket::{Request, State};
use std::sync::atomic::{AtomicUsize, Ordering};

#[get("/rate_limited")]
async fn rate_limited(counter: &State<AtomicUsize>) -> String {
    let count = counter.fetch_add(1, Ordering::Relaxed);
    format!("Request number {}", count)
}

#[launch]
fn rocket() -> _ {
    let counter = AtomicUsize::new(0);

    rocket::build()
        .manage(counter)
        .mount("/", routes![rate_limited])
}
504 chars
21 lines

related categories

gistlibby LogSnag