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:
parent
4272586f0c
commit
4df66d1e8a
1
Cargo.lock
generated
1
Cargo.lock
generated
@ -4105,6 +4105,7 @@ version = "1.0.0"
|
||||
dependencies = [
|
||||
"actix-http",
|
||||
"actix-web",
|
||||
"actix-web-lab",
|
||||
"env_logger",
|
||||
"futures-util",
|
||||
"log",
|
||||
|
@ -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"] }
|
||||
|
@ -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."
|
||||
|
Loading…
Reference in New Issue
Block a user