How to use HttpMessage extensions? (actix-web)

I'm playing around with actix-web, trying out a few things. The issue I've bumped into was writing two wrapper functions using extensions_mut and extensions on HttpMessage (for ServiceRequest).

I think that the following will put an u32 in a requests extensions:

.wrap_fn(|req, srv| {
    req.extensions_mut().insert(42_u32);
    srv.call(req)
})

However, when I later (i.e. below) try to get it out again with this code:

.wrap_fn(|req, srv| {
    {
        let exts = req.extensions();
        let val = exts.get::<u32>();
        println!("found: {:?}", val);
    }
    srv.call(req)

I get a None.

Have I misunderstood the API and what it offers, or is it just a silly mistake in my code?

Oh, now I feel silly :grinning_face_with_smiling_eyes:

By doing some println! debugging I realised that I need to do the wrapping bottom-up, i.e.

App::new()
    .wrap_fn(|req, srv| {
        println!("get value");
        {
            let exts = req.extensions();
            let val = exts.get::<u32>();
            println!("found: {:?}", val);
        }
        srv.call(req)
    })
    .wrap_fn(|req, srv| {
        println!("insert value");
        req.extensions_mut().insert::<u32>(42);
        srv.call(req)
    })
    .service(...)
2 Likes