omjadas / hudsucker

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

How to obtain the request URI address in `HttpHandler::handle_response`? #67

Closed grnmeira closed 1 year ago

grnmeira commented 1 year ago

I was giving it a try today and was quite curious if it was possible to have the request's URI address available in HttpHandler::handle_response. It looks like the Response type used is a hyper::Response, which doesn't contain any information about the URI. Is there a way to obtain it? It's fairly handy to have that information available also while handling responses (for filtering, for rexample).

In the proxy implementation, where HttpHandler::handle_response is called, looks like Request (which contains the URI) information is readily available, I'd be happy to provide a PR if needed.

Great work, by the way, it was super easy to set it up and start working with it. Thanks!

omjadas commented 1 year ago

If you need any information from the Request while processing the Response, you can store it in the handler itself.

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

#[derive(Clone)]
struct Handler {
    uri: Option<Uri>,
}

impl Handler {
    fn new() -> Self {
        Handler { uri: None }
    }
}

#[async_trait]
impl HttpHandler for Handler {
    async fn handle_request(
        &mut self,
        _ctx: &HttpContext,
        req: Request<Body>,
    ) -> RequestOrResponse {
        self.uri = Some(req.uri().clone());
        req.into()
    }

    async fn handle_response(&mut self, _ctx: &HttpContext, res: Response<Body>) -> Response<Body> {
        // do something with self.uri
        res
    }
}