Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to Get Response Body in middleware #178

Open
caibirdme opened this issue Jul 31, 2024 · 2 comments
Open

How to Get Response Body in middleware #178

caibirdme opened this issue Jul 31, 2024 · 2 comments
Labels
enhancement New feature or request

Comments

@caibirdme
Copy link

I want to impl a middleware that can log request and response body

#[async_trait]
impl Middleware for LoggingMiddlware {
    async fn handle(
        &self,
        req: Request,
        extensions: &mut Extensions,
        next: Next<'_>,
    ) -> ReqResult<Response> {
        req.body().clone()
			.and_then(|b| b.as_bytes())
			.and_then(|v| {
				println!("Request: {:?}", std::str::from_utf8(v).unwrap());
				Some(())
			});
        let res = next.run(req, extensions).await;
        // since response is a future
        // how can I get its response body without changing it?
        res
    }
}
@caibirdme caibirdme added the enhancement New feature or request label Jul 31, 2024
@urosjovanovic
Copy link

Any updates on this one? I had the same scenario, trying to log the response body within the logger middleware but the current design just doesn't support this. In the end, I needed to pull out my logging logic out of the middleware and wrap around HTTP client's execute method in order to invoke the .bytes() method.

I guess the culprit is that body streaming methods such as .bytes() are consuming the whole Response object (self) so it becomes unusable after it is invoked.

@lcmgh
Copy link

lcmgh commented Oct 17, 2024

I am interested in adding a body trace to my OTLP span but that seems even more difficult as fn on_request_end ofReqwestOtelSpanBackend is not even async.

https://docs.rs/reqwest-tracing/latest/reqwest_tracing/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Development

No branches or pull requests

3 participants