Skip to main content

basic/
rate_limit.rs

1use afire::{extension::RateLimiter, Content, Method, Middleware, Response, Server, Status};
2
3use crate::Example;
4
5// You can run this example with `cargo run --example basic -- rate_limit`
6
7// Use some of afire's built-in middleware to log requests.
8pub struct RateLimit;
9
10impl Example for RateLimit {
11    fn name(&self) -> &'static str {
12        "rate_limit"
13    }
14
15    fn exec(&self) {
16        // Create a new Server instance on localhost port 8080
17        let mut server = Server::<()>::new("localhost", 8080);
18
19        // Define a handler for GET "/"
20        server.route(Method::GET, "/", |_req| {
21            Response::new().text("Hello World!").content(Content::TXT)
22        });
23
24        // For this example, we'll limit requests to 1 every 2 seconds
25
26        // Make a new Ratelimater
27        // Default Limit is 10
28        // Default Timeout is 60 sec
29        RateLimiter::new()
30            // Override the Limit to 1
31            .limit(1)
32            // Override the timeout to 2
33            .timeout(2)
34            // Override the Handler
35            .handler(Box::new(|_req| {
36                Some(
37                    Response::new()
38                        .status(Status::TooManyRequests)
39                        .text("AHHHH!!! Too Many Requests")
40                        .content(Content::TXT),
41                )
42            }))
43            // Attach to the server
44            .attach(&mut server);
45
46        // Now if you goto http://localhost:8080/ and reload a bunch of times,
47        // you'll see the rate limiter kicking in.
48
49        // Start the server
50        // This will block the current thread
51        server.start().unwrap();
52    }
53}