From 4df66d1e8a1613de293fc8bef8783941dafef1d1 Mon Sep 17 00:00:00 2001 From: Rob Ede Date: Sat, 17 Dec 2022 22:10:51 +0000 Subject: [PATCH] add from_fn to mdidleware example --- Cargo.lock | 1 + middleware/middleware/Cargo.toml | 3 ++- middleware/middleware/src/main.rs | 28 ++++++++++++++++++---------- 3 files changed, 21 insertions(+), 11 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3f644330..a85007f5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4105,6 +4105,7 @@ version = "1.0.0" dependencies = [ "actix-http", "actix-web", + "actix-web-lab", "env_logger", "futures-util", "log", diff --git a/middleware/middleware/Cargo.toml b/middleware/middleware/Cargo.toml index c820061f..1d4cb5c6 100644 --- a/middleware/middleware/Cargo.toml +++ b/middleware/middleware/Cargo.toml @@ -4,8 +4,9 @@ version = "1.0.0" edition = "2021" [dependencies] -actix-web = "4" actix-http = "3" +actix-web = "4" +actix-web-lab = "0.18" env_logger = "0.10" futures-util = { version = "0.3.17", default-features = false, features = ["std"] } diff --git a/middleware/middleware/src/main.rs b/middleware/middleware/src/main.rs index 927c2dc9..31171bde 100644 --- a/middleware/middleware/src/main.rs +++ b/middleware/middleware/src/main.rs @@ -1,11 +1,26 @@ -use actix_web::{dev::Service, web, App, HttpServer}; -use futures_util::FutureExt as _; +use std::time::Duration; + +use actix_http::body::MessageBody; +use actix_web::{dev, rt::time, web, App, Error, HttpServer}; +use actix_web_lab::middleware::{from_fn, Next}; mod read_request_body; mod read_response_body; mod redirect; mod simple; +// See more examples of from_fn middleware here: +// https://github.com/robjtede/actix-web-lab/blob/main/actix-web-lab/examples/from_fn.rs +async fn timeout_10secs( + req: dev::ServiceRequest, + next: Next, +) -> Result, Error> { + match time::timeout(Duration::from_secs(10), next.call(req)).await { + Ok(res) => res, + Err(_err) => Err(actix_web::error::ErrorRequestTimeout("")), + } +} + #[actix_web::main] async fn main() -> std::io::Result<()> { env_logger::init_from_env(env_logger::Env::new().default_filter_or("info")); @@ -18,14 +33,7 @@ async fn main() -> std::io::Result<()> { .wrap(read_request_body::Logging) .wrap(read_response_body::Logging) .wrap(simple::SayHi) - .wrap_fn(|req, srv| { - println!("Hi from start. You requested: {}", req.path()); - - srv.call(req).map(|res| { - println!("Hi from response"); - res - }) - }) + .wrap(from_fn(timeout_10secs)) .service(web::resource("/login").to(|body: String| async move { println!("request body (handler): {body}"); "You are on /login. Go to src/redirect.rs to change this behavior."