Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use middleware on actix web 4?

I am trying to use a simple Middleware with ActixWeb 4:

HttpServer::new(
    move || {
        let app_state = AppState {
            db_helper: external_db.clone(),
            client: Client::new(),
        };
        App::new()
            .wrap_fn(|req, srv| {
                let header = req.headers().get("Test").unwrap().to_str().unwrap().to_owned();
                let fut = srv.call(req);
                async move {
                    let res = fut.await?;
                    println!("{:#?}", header);
                    Ok(res)
                }
            })
            .app_data(web::Data::new(app_state))
            .service(web::scope(API_PATH)
                .service(user_controller::user_scope())
            )
    })
    .bind(SERVER_URL)?
    .run();

It's a very simple sample from their tutorial. However, I always get an error:

 let fut = srv.call(req);
               ^^^^ method cannot be called on `&actix_web::app_service::AppRouting` due to unsatisfied trait bounds

How can I solve this?

like image 791
Kingfisher Phuoc Avatar asked Oct 20 '25 02:10

Kingfisher Phuoc


1 Answers

You need to bring the trait into scope with

use actix_web::dev::Service;
like image 116
Luciano Bestia Avatar answered Oct 22 '25 04:10

Luciano Bestia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!