omjadas / hudsucker

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

How to serliaize hudsucker::Body to bytes? #110

Closed domehead100 closed 4 months ago

domehead100 commented 4 months ago

Hi, I'm trying out the current main branch, and since the update to hyper 1.x, I'm having a hard time figuring out how to serialize the request or response body (hudsucker::body) to a byte vec.

I'm not super well versed in rust, so sorry if this is dumb.

Any help or suggestions would be much appreciated.

omjadas commented 4 months ago

You can do something like below using http-body-util.

use http_body_util::{BodyExt, Full};
use hudsucker::{
    hyper::{body::Bytes, Request, Response},
    *,
};

#[derive(Clone)]
struct Handler;

impl HttpHandler for Handler {
    async fn handle_request(
        &mut self,
        _ctx: &HttpContext,
        req: Request<Body>,
    ) -> RequestOrResponse {
        let (parts, body) = req.into_parts();
        let bytes: Bytes = body.collect().await.unwrap().to_bytes();

        // use bytes

        Request::from_parts(parts, Full::new(bytes).into()).into()
    }

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

        // use bytes

        Response::from_parts(parts, Full::new(bytes).into())
    }
}
domehead100 commented 4 months ago

OMG, thanks so much. Works perfectly of course. I guess that I was getting thrown off by the hudsucker::body wrapper type and not knowing how to use http_util.

Thanks again.