> {:<12} - Ctx: extensions {:?}", "MIDDLEWARE", parts.extensions.clone() ); the output is ->> MIDDLEWARE - Ctx: extensions " /> > {:<12} - Ctx: extensions {:?}", "MIDDLEWARE", parts.extensions.clone() ); the output is ->> MIDDLEWARE - Ctx: extensions " /> > {:<12} - Ctx: extensions {:?}", "MIDDLEWARE", parts.extensions.clone() ); the output is ->> MIDDLEWARE - Ctx: extensions "/>

how can I print all the extensions values on Axum Extensions Struct?

66 views Asked by At

If I run this

        println!(
        "->> {:<12} - Ctx: extensions {:?}",
        "MIDDLEWARE",
        parts.extensions.clone()
        );

the output is

->> MIDDLEWARE   - Ctx: extensions Extensions

I know it has 6 extensions when I run

parts.extensions.len()

I created only one with one struct called CTX

I know how to return my one, but I want a way of debug printing all the values inside the extension, The extension uses a map with types as keys, and I want to see all the keys and values inside.

I didn't find anything inside the doc of the struct Extension, I am a beginner in Rust, maybe it has a way direct by code. https://docs.rs/axum/latest/axum/struct.Extension.html

1

There are 1 answers

0
kmdreko On BEST ANSWER

You cannot.

Extensions stores its data in (essentially) a HashMap<TypeId, Box<dyn Any>>. There is no requirement that the values stored within implement Debug, Display, or any other representable trait. And you can't get the concrete type from a Box<dyn Any> unless you already know (statically) what type it could be. Equally, you can't get any generic information from the TypeId even if the Extensions exposed it.

So unfortunately, your only insight would be from querying what types are relevant to you and print those using a series of if let Some(ext) = parts.extensions.get::<MyExt>() { ... } or similar.