From d5f213b2707f5ed268a6d46f62ffd51f67206bf4 Mon Sep 17 00:00:00 2001 From: Emi Tatsuo Date: Sat, 21 Nov 2020 17:20:32 -0500 Subject: [PATCH] Add ratelimiting example Was really supposed to add this earlier but I forgot about it. Oops --- examples/ratelimits.rs | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 examples/ratelimits.rs diff --git a/examples/ratelimits.rs b/examples/ratelimits.rs new file mode 100644 index 0000000..b9cf2ab --- /dev/null +++ b/examples/ratelimits.rs @@ -0,0 +1,39 @@ +use anyhow::*; +use futures_core::future::BoxFuture; +use futures_util::FutureExt; +use log::LevelFilter; +use northstar::{Server, Request, Response, GEMINI_PORT, Document}; + +#[tokio::main] +async fn main() -> Result<()> { + env_logger::builder() + .filter_module("northstar", LevelFilter::Debug) + .init(); + + let two = std::num::NonZeroU32::new(2).unwrap(); + + Server::bind(("localhost", GEMINI_PORT)) + .add_route("/", handle_request) + .rate_limit("/limit", northstar::Quota::per_minute(two)) + .serve() + .await +} + +fn handle_request(request: Request) -> BoxFuture<'static, Result> { + async move { + let mut document = Document::new(); + + if let Some("limit") = request.trailing_segments().get(0).map(String::as_str) { + document.add_text("You're on a rate limited page!") + .add_text("You can only access this page twice per minute"); + } else { + document.add_text("You're on a normal page!") + .add_text("You can access this page as much as you like."); + } + document.add_blank_line() + .add_link("/limit", "Go to rate limited page") + .add_link("/", "Go to a page that's not rate limited"); + Ok(Response::document(document)) + } + .boxed() +}