Search code examples
rustactix-web

Get the app state in FromRequest implementation


I have an actix web server and I want to get the state of my server within a FromRequest implementation.

I'd tried something like:

impl FromRequest for User {
    type Config = ();
    type Error = Error;
    type Future = Pin<Box<dyn Future<Output = Result<User, actix_web::Error>>>>;

    fn from_request(req: &HttpRequest, pl: &mut Payload, state: web::Data<State>) -> Self::Future {
       ...
    }
}

But of course, this doesn't work since from_request asks for 2 arguments only, not 3.


Solution

  • You can do:

    fn from_request(req: &HttpRequest, pl: &mut Payload) -> Self::Future {
       let _state = req.app_data::<Data<State>>();
       ....
    }
    

    See docs for app_data