From 50c3e75bc32baf12b7df549170ee07d7bf47e1b8 Mon Sep 17 00:00:00 2001 From: Ross Date: Wed, 11 Sep 2024 22:51:39 +0900 Subject: [PATCH] Added documentation for `from_fn` and `wrap` in middleware page (#451) * Added documentation for from_fn and wrap in middleware page * Update docs/middleware.md --------- Co-authored-by: Rob Ede --- docs/middleware.md | 6 ++++++ examples/middleware/src/from_fn.rs | 24 ++++++++++++++++++++++++ examples/middleware/src/main.rs | 1 + 3 files changed, 31 insertions(+) create mode 100644 examples/middleware/src/from_fn.rs diff --git a/docs/middleware.md b/docs/middleware.md index e98273c..a8551a4 100644 --- a/docs/middleware.md +++ b/docs/middleware.md @@ -27,6 +27,10 @@ Alternatively, for simple use cases, you can use [_wrap_fn_][wrap_fn] to create +You can also use [_from_fn_][from_fn] to in combination with [_wrap_][wrap] to create a function as middlware. + + + > Actix Web provides several useful middleware, such as _logging_, _user sessions_, _compress_, etc. **Warning: if you use `wrap()` or `wrap_fn()` multiple times, the last occurrence will be executed first.** @@ -111,3 +115,5 @@ You can use the `ErrorHandlers::handler()` method to register a custom error han [servicetrait]: https://docs.rs/actix-web/4/actix_web/dev/trait.Service.html [transformtrait]: https://docs.rs/actix-web/4/actix_web/dev/trait.Transform.html [wrap_fn]: https://docs.rs/actix-web/4/actix_web/struct.App.html#method.wrap_fn +[from_fn]: https://docs.rs/actix-web/4/actix_web/middleware/fn.from_fn.html +[wrap]: https://docs.rs/actix-web/4/actix_web/struct.App.html#method.wrap diff --git a/examples/middleware/src/from_fn.rs b/examples/middleware/src/from_fn.rs new file mode 100644 index 0000000..2c5ccc0 --- /dev/null +++ b/examples/middleware/src/from_fn.rs @@ -0,0 +1,24 @@ +#![allow(dead_code, unused_variables)] + +// +use actix_web::{ + body::MessageBody, + dev::{ServiceRequest, ServiceResponse}, + middleware::{from_fn, Next}, + App, Error, +}; + +async fn my_midleware( + req: ServiceRequest, + next: Next, +) -> Result, Error> { + // pre-processing + next.call(req).await + // post-processing +} + +#[actix_web::main] +async fn main() { + let app = App::new().wrap(from_fn(my_midleware)); +} +// diff --git a/examples/middleware/src/main.rs b/examples/middleware/src/main.rs index 3aadfd6..a59268e 100644 --- a/examples/middleware/src/main.rs +++ b/examples/middleware/src/main.rs @@ -1,5 +1,6 @@ pub mod default_headers; pub mod errorhandler; +pub mod from_fn; pub mod logger; pub mod user_sessions; pub mod wrap_fn;