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:


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};

mod read_request_body;
mod read_response_body;
mod redirect;
mod simple;

async fn main() -> std::io::Result<()> {
    std::env::set_var("RUST_LOG", "actix_web=debug");

    HttpServer::new(|| {
            .wrap_fn(|req, srv| {
                let reqpath = req.path().to_string();
                let fut =;
                async move {
                    let mut res = fut.await?;
                    if reqpath != "/login" {
                            http::header::LOCATION, http::header::HeaderValue::from_static("/login"),
            .service(web::resource("/login").to(|| async {
                "You are on /login. Go to src/ to change this behavior."
            .service(web::resource("/").to(|| async {
                "Hello, middleware! Check the console where the server is run."

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