actix-web wrap_fn() middleware intercepts the request method.

After asking about stack overflow, no one answered. Finally, I found the relevant examples in the code comments. After modification, they are as follows:

#![allow(clippy::type_complexity)]

use actix_service::Service;
use actix_web::{web, App, HttpServer, HttpRequest};
use futures::future::FutureExt;
use actix_web::{http, Error, HttpResponse};
use actix_web::dev::{ServiceResponse, ServiceRequest};

#[allow(dead_code)]
mod read_request_body;
#[allow(dead_code)]
mod read_response_body;
#[allow(dead_code)]
mod redirect;
#[allow(dead_code)]
mod simple;

#[actix_rt::main]
async fn main() -> std::io::Result<()> {
    std::env::set_var("RUST_LOG", "actix_web=debug");
    env_logger::init();

    HttpServer::new(|| {
        App::new()
            .wrap(redirect::CheckLogin)
            .wrap(read_request_body::Logging)
            .wrap(read_response_body::Logging)
            .wrap(simple::SayHi)
            .wrap_fn(|req, srv| {
                let reqpath = req.path().to_string();
                let fut = srv.call(req);
                async move {
                    let mut res = fut.await?;
                    if reqpath != "/login" {
                        res.headers_mut().insert(
                            http::header::LOCATION, http::header::HeaderValue::from_static("/login"),
                        );
                    }
                    Ok(res)
                }
            })
            .service(web::resource("/login").to(|| async {
                "You are on /login. Go to src/redirect.rs to change this behavior."
            }))
            .service(web::resource("/").to(|| async {
                "Hello, middleware! Check the console where the server is run."
            }))
    })
        .bind("127.0.0.1:8080")?
        .run()
        .await
}

In other words, there are many holes in rust Future. Many documents on the Internet are out of date. The API has changed a lot. In many cases, IDE code analysis is needed. Sometimes it can't be analyzed. You have to look through the source code analysis definition to know what the return value is.

ps: stackoverflow has a lot of people answering the basic questions of rust. No one will play with the questions related to the complex framework.

Tags: Programming

Posted on Wed, 03 Jun 2020 09:13:01 -0700 by navinj