Struct afire::extension::RateLimiter

source ยท
pub struct RateLimiter { /* private fields */ }
Expand description

Limit the amount of requests handled by the server.

Implementationsยง

sourceยง

impl RateLimiter

source

pub fn new() -> RateLimiter

Make a new RateLimiter.

Default limit is 10 and timeout is 60

Examples found in repository?
examples/basic/rate_limit.rs (line 29)
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
    fn exec(&self) {
        // Create a new Server instance on localhost port 8080
        let mut server = Server::<()>::new("localhost", 8080);

        // Define a handler for GET "/"
        server.route(Method::GET, "/", |_req| {
            Response::new().text("Hello World!").content(Content::TXT)
        });

        // For this example, we'll limit requests to 1 every 2 seconds

        // Make a new Ratelimater
        // Default Limit is 10
        // Default Timeout is 60 sec
        RateLimiter::new()
            // Override the Limit to 1
            .limit(1)
            // Override the timeout to 2
            .timeout(2)
            // Override the Handler
            .handler(Box::new(|_req| {
                Some(
                    Response::new()
                        .status(Status::TooManyRequests)
                        .text("AHHHH!!! Too Many Requests")
                        .content(Content::TXT),
                )
            }))
            // Attach to the server
            .attach(&mut server);

        // Now if you goto http://localhost:8080/ and reload a bunch of times,
        // you'll see the rate limiter kicking in.

        // Start the server
        // This will block the current thread
        server.start().unwrap();
    }
source

pub fn limit(self, limit: u64) -> RateLimiter

Set the request limit per timeout Attach the rate limiter to a server.

Example
// Import Lib
use afire::{Server, extension::RateLimiter, Middleware};

// Create a new server
let mut server = Server::<()>::new("localhost", 1234);

// Add a rate limiter
RateLimiter::new()
    // Override limit to 100 requests
    .limit(100)
    // Attach it to the server
    .attach(&mut server);

// Start Server
// This is blocking
server.start().unwrap();
Examples found in repository?
examples/basic/rate_limit.rs (line 31)
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
    fn exec(&self) {
        // Create a new Server instance on localhost port 8080
        let mut server = Server::<()>::new("localhost", 8080);

        // Define a handler for GET "/"
        server.route(Method::GET, "/", |_req| {
            Response::new().text("Hello World!").content(Content::TXT)
        });

        // For this example, we'll limit requests to 1 every 2 seconds

        // Make a new Ratelimater
        // Default Limit is 10
        // Default Timeout is 60 sec
        RateLimiter::new()
            // Override the Limit to 1
            .limit(1)
            // Override the timeout to 2
            .timeout(2)
            // Override the Handler
            .handler(Box::new(|_req| {
                Some(
                    Response::new()
                        .status(Status::TooManyRequests)
                        .text("AHHHH!!! Too Many Requests")
                        .content(Content::TXT),
                )
            }))
            // Attach to the server
            .attach(&mut server);

        // Now if you goto http://localhost:8080/ and reload a bunch of times,
        // you'll see the rate limiter kicking in.

        // Start the server
        // This will block the current thread
        server.start().unwrap();
    }
source

pub fn timeout(self, timeout: u64) -> RateLimiter

Set the Ratelimit refresh period

Example
// Import Lib
use afire::{Server, extension::RateLimiter, Middleware};

// Create a new server
let mut server = Server::<()>::new("localhost", 1234);

// Add a rate limiter
RateLimiter::new()
    // Override timeout to 60 seconds
    .timeout(60)
    // Attach it to the server
    .attach(&mut server);

// Start Server
// This is blocking
server.start().unwrap();
Examples found in repository?
examples/basic/rate_limit.rs (line 33)
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
    fn exec(&self) {
        // Create a new Server instance on localhost port 8080
        let mut server = Server::<()>::new("localhost", 8080);

        // Define a handler for GET "/"
        server.route(Method::GET, "/", |_req| {
            Response::new().text("Hello World!").content(Content::TXT)
        });

        // For this example, we'll limit requests to 1 every 2 seconds

        // Make a new Ratelimater
        // Default Limit is 10
        // Default Timeout is 60 sec
        RateLimiter::new()
            // Override the Limit to 1
            .limit(1)
            // Override the timeout to 2
            .timeout(2)
            // Override the Handler
            .handler(Box::new(|_req| {
                Some(
                    Response::new()
                        .status(Status::TooManyRequests)
                        .text("AHHHH!!! Too Many Requests")
                        .content(Content::TXT),
                )
            }))
            // Attach to the server
            .attach(&mut server);

        // Now if you goto http://localhost:8080/ and reload a bunch of times,
        // you'll see the rate limiter kicking in.

        // Start the server
        // This will block the current thread
        server.start().unwrap();
    }
source

pub fn handler( self, handler: Box<dyn Fn(&Request) -> Option<Response> + Send + Sync> ) -> RateLimiter

Define a Custom Handler for when a client has exceeded the ratelimit. If the handler returns None, the request will be processed normally.

Example
// Import Lib
use afire::{Server, Response, extension::RateLimiter, Middleware};

// Create a new server
let mut server = Server::<()>::new("localhost", 1234);

// Add a rate limiter
RateLimiter::new()
    // Override the handler for requests exceeding the limit
    .handler(Box::new(|_req| Some(Response::new().text("much request"))))
    // Attach it to the server
    .attach(&mut server);

// Start Server
// This is blocking
server.start().unwrap();
Examples found in repository?
examples/basic/rate_limit.rs (lines 35-42)
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
    fn exec(&self) {
        // Create a new Server instance on localhost port 8080
        let mut server = Server::<()>::new("localhost", 8080);

        // Define a handler for GET "/"
        server.route(Method::GET, "/", |_req| {
            Response::new().text("Hello World!").content(Content::TXT)
        });

        // For this example, we'll limit requests to 1 every 2 seconds

        // Make a new Ratelimater
        // Default Limit is 10
        // Default Timeout is 60 sec
        RateLimiter::new()
            // Override the Limit to 1
            .limit(1)
            // Override the timeout to 2
            .timeout(2)
            // Override the Handler
            .handler(Box::new(|_req| {
                Some(
                    Response::new()
                        .status(Status::TooManyRequests)
                        .text("AHHHH!!! Too Many Requests")
                        .content(Content::TXT),
                )
            }))
            // Attach to the server
            .attach(&mut server);

        // Now if you goto http://localhost:8080/ and reload a bunch of times,
        // you'll see the rate limiter kicking in.

        // Start the server
        // This will block the current thread
        server.start().unwrap();
    }

Trait Implementationsยง

sourceยง

impl Debug for RateLimiter

sourceยง

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
sourceยง

impl Default for RateLimiter

sourceยง

fn default() -> Self

Returns the โ€œdefault valueโ€ for a type. Read more
sourceยง

impl Middleware for RateLimiter

sourceยง

fn pre(&self, req: &mut Request) -> MiddleResult

Middleware to run Before Routes
sourceยง

fn end(&self, req: &Request, _res: &Response)

Middleware ot run after the response has been handled
sourceยง

fn pre_raw(&self, req: &mut Result<Request>) -> MiddleResult

Middleware to run before routes. Because this is the raw version of Middleware::pre, it is passed a Result. The default implementation calls Middleware::pre if the Result is Ok.
sourceยง

fn post_raw( &self, req: Result<Rc<Request>>, res: &mut Result<Response> ) -> MiddleResult

Middleware to run after routes. Because this is the raw version of Middleware::post, it is passed a Result. The default implementation calls Middleware::post if the Result is Ok.
sourceยง

fn post(&self, _req: &Request, _res: &mut Response) -> MiddleResult

Middleware to run After Routes
sourceยง

fn end_raw(&self, req: &Result<Request>, res: &Result<Response>)

Middleware to run after the response has been handled. Because this is the raw version of Middleware::end, it is passed a Result. The default implementation calls Middleware::end if the Result is Ok.
sourceยง

fn attach<State>(self, server: &mut Server<State>)where Self: 'static + Send + Sync + Sized, State: 'static + Send + Sync,

Attach Middleware to a Server. If you want to get a reference to the serverโ€™s state in your middleware state, you should override this method.

Auto Trait Implementationsยง

Blanket Implementationsยง

sourceยง

impl<T> Any for Twhere T: 'static + ?Sized,

sourceยง

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
sourceยง

impl<T> Borrow<T> for Twhere T: ?Sized,

sourceยง

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
sourceยง

impl<T> BorrowMut<T> for Twhere T: ?Sized,

sourceยง

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
sourceยง

impl<T> From<T> for T

sourceยง

fn from(t: T) -> T

Returns the argument unchanged.

sourceยง

impl<T, U> Into<U> for Twhere U: From<T>,

sourceยง

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

sourceยง

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

ยง

type Error = Infallible

The type returned in the event of a conversion error.
sourceยง

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
sourceยง

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

ยง

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
sourceยง

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.