actix-web wrap_fn() middleware 拦截请求方法。

原创
2020/06/03 17:44
阅读数 614

问了一圈 stackoverflow,没有人回答,最后在代码注释里找到了相关范例,修改后如下:

#![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
}

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部