Modify response in Rust tower Service

28 views Asked by At

I'm new to the Rust language. I want to write a performant reverse proxy that modifies requests and responses on the fly according to a configuration. I'm using Tokio, Hyper, and Tower with their Service Layers. This is my code:

#[derive(Debug, Clone)]
pub struct Middleware<S> {
    inner: S,
}
impl<S> Middleware<S> {
    pub fn new(inner: S) -> Self {
        Middleware { inner }
    }
}
type Req = Request<Incoming>;
impl<S> Service<Req> for Middleware<S>
where
    S: Service<Req> + Clone,
{
    type Response = S::Response;

    type Error = S::Error;

    type Future = S::Future;

    fn poll_ready(
        &mut self,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(cx)
    }

    fn call(&mut self, req: Req) -> Self::Future {
        println!(
            "processing request: {} {} {}",
            req.method(),
            req.uri().path(),
            req.uri().query().unwrap()
        );
        //1. make the call
        self.inner.call(req)
        
        //2. Get response
        //3. Modify it
        //4. Return new response
    }
}

I assume I need to get Future returned in the call: let fut = self.inner.call(req) and somehow extract and modify body and/or response headers and then return another Future.

I might be wrong here, and this is not the way to do it, or maybe there is another, better way to achieve my goal.

Could someone please advise on how to archive that?

0

There are 0 answers