actix_state_guards/
lib.rs

1/*!
2This crate provides a more flexible guard function for the [`actix-web`] framework.
3
4The [`Guard`] acts as a gatekeeper for a specific scope and governs over which request is allowed to pass.
5
6Guards can accept application state as well as types that implement the [`FromReqeust`] trait as parameters.
7They can also execute asynchrones code inside them.
8# Example
9
10```rust
11# use actix_state_guards::UseStateGuardOnApp;
12# use std::fmt::Display;
13# use std::sync::Mutex;
14# use actix_web::App;
15# use actix_web::HttpServer;
16# use actix_web::Responder;
17# use actix_web::ResponseError;
18# use actix_web::{get, web};
19#[derive(Debug)]
20pub struct CounterError();
21
22impl Display for CounterError {
23    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
24        f.write_str("Error: Counter is over 100")
25    }
26}
27
28impl ResponseError for CounterError {}
29
30#[get("/count")]
31async fn count(counter: web::Data<Mutex<u32>>) -> impl Responder {
32    let mut counter = counter.lock().unwrap();
33    *counter += 1;
34    counter.to_string()
35}
36
37#[actix_web::main]
38async fn main() -> Result<(), Box<dyn std::error::Error>> {
39    Ok(HttpServer::new(move || {
40        App::new()
41            .app_data(web::Data::new(Mutex::new(0u32)))
42            .use_state_guard(
43                |counter: web::Data<Mutex<u32>>| async move {
44                    if *counter.lock().unwrap() < 100 {
45                        Ok(())
46                    } else {
47                        // by returning the error case of the result enum we signal that this
48                        // request shall not be allowed to pass on to the scope wrapped
49                        Err(CounterError())
50                    }
51                },
52                web::scope("").service(count),
53            )
54    })
55    .bind(("127.0.0.1", 8080))?
56    .run()
57    .await?)
58}
59```
60*/
61pub use errors::*;
62pub use guard::*;
63pub use transform::*;
64pub use use_state_guard::*;
65
66mod errors;
67mod guard;
68mod middleware;
69mod transform;
70mod use_state_guard;