Accessing response extensions #776
-
Hi, I can use For example: Router::new()
.route(
"/user/:id",
get(handlers::get_user).layer(AndThenLayer::new(middleware::hash_user)),
)
...
.layer(AddExtensionLayer::new(Arc::new(app_config))) middleware.rs fn get_hash_prefix(response: &Response<BoxBody>) -> &str {
response
.extensions()
.get::<Arc<AppConfig>>()
.map(|config| config.hash_prefix.as_str())
.unwrap_or("default_prefix")
}
pub async fn hash_user(
response: Response<BoxBody>,
) -> Result<Response<BoxBody>, Infallible> {
let prefix = get_hash_prefix(&response).to_owned();
event!(target: FRAMEWORK_TARGET, Level::DEBUG, "Using hash prefix: {prefix}");
if response.status().is_success() {
let result = response.map(move |body| {
boxed(body.map_data(move |bytes| {
match serde_json::from_slice(&bytes)
.map(|b: User| b.hash(&prefix))
.ok()
{
Some(hashed) => Bytes::from(serde_json::to_vec(&hashed).unwrap()),
None => bytes,
}
}))
});
Ok(result)
} else {
Ok(response)
}
} The |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Extensions on the request aren't automatically copied to the response. You have to do that manually for the necessary extensions. |
Beta Was this translation helpful? Give feedback.
-
Ok. That's what I thought. In this case I opted to create middleware via |
Beta Was this translation helpful? Give feedback.
Extensions on the request aren't automatically copied to the response. You have to do that manually for the necessary extensions.