omjadas / hudsucker

Intercepting HTTP/S proxy
https://crates.io/crates/hudsucker
Apache License 2.0
205 stars 34 forks source link

How to get the original data of Response body? #81

Closed bida2015 closed 11 months ago

bida2015 commented 11 months ago

Thank you for making such a great box. I just learned Rust. I want to get the raw body data of the response based on this. I'm using example/log.rs. Printed res displays the body value as Body (Streaming). For example, when the content-type is application/json, I need to get the original json data. How can I decode it into raw data? Hope you can give me a complete example, thank you!

Response { status: 200, version: HTTP/2.0, headers: {"content-length": "1347", "content-type": "application/json; charset=utf-8", "etag": "229858941_501691865", "strict-transport-security": "max-age=2592000", "x-content-type-options": "nosniff", "x-exp-trackingid": "40508587-0516-427b-a2c9-e02a22506ce6", "x-cache": "CONFIG_NOCACHE", "access-control-allow-origin": "*", "x-msedge-ref": "Ref A: B0BD5EC4DAC04E828DCBCFD3F4E9DAD6 Ref B: TYO01EDGE2009 Ref C: 2023-09-24T13:33:31Z", "date": "Sun, 24 Sep 2023 13:33:30 GMT"}, body: Body(Streaming) }

omjadas commented 11 months ago

The easiest way is to use hyper::body::to_bytes. You may also need to use decode_request/decode_response if the bodies are compressed.

use hudsucker::{
    async_trait::async_trait,
    hyper::{Body, Request, Response},
    *,
};

#[derive(Clone)]
struct Handler;

#[async_trait]
impl HttpHandler for Handler {
    async fn handle_request(
        &mut self,
        _ctx: &HttpContext,
        req: Request<Body>,
    ) -> RequestOrResponse {
        let req = decode_request(req).unwrap();
        let (req, mut body) = req.into_parts();
        let bytes = hyper::body::to_bytes(&mut body).await.unwrap();

        // use bytes

        Request::from_parts(req, body).into()
    }

    async fn handle_response(&mut self, _ctx: &HttpContext, res: Response<Body>) -> Response<Body> {
        let res = decode_response(res).unwrap();
        let (res, mut body) = res.into_parts();
        let bytes = hyper::body::to_bytes(&mut body).await.unwrap();

        // use bytes

        Response::from_parts(res, body)
    }
}
bida2015 commented 11 months ago

Thanks for taking the time to reply! solved!