1
0
mirror of https://github.com/actix/examples synced 2024-11-27 16:02:57 +01:00

add from_fn to mdidleware example

This commit is contained in:
Rob Ede 2022-12-17 22:10:51 +00:00
parent 4272586f0c
commit 4df66d1e8a
No known key found for this signature in database
GPG Key ID: 97C636207D3EF933
3 changed files with 21 additions and 11 deletions

1
Cargo.lock generated
View File

@ -4105,6 +4105,7 @@ version = "1.0.0"
dependencies = [
"actix-http",
"actix-web",
"actix-web-lab",
"env_logger",
"futures-util",
"log",

View File

@ -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"] }

View File

@ -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<impl MessageBody + 'static>,
) -> Result<dev::ServiceResponse<impl MessageBody>, 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."