danielSanchezQ / warp-reverse-proxy

Fully composable warp filter that can be used as a reverse proxy.
https://github.com/danielSanchezQ/warp-reverse-proxy
MIT License
48 stars 18 forks source link

How to modify the body of a post before forwarding the request? #46

Closed gpfeifer closed 2 years ago

gpfeifer commented 2 years ago

Hi, First of all: Great work! I want to modify the body (and the headers) of a post request before the request is forwarded. Any hints? Best regards Gregor

danielSanchezQ commented 2 years ago

@gpfeifer

Leveraging from the docs example, you can wrap the forwarding call in a closure for example and modify whatever you need:

use warp::Filter;
use warp::hyper::Body;
use warp_reverse_proxy::{extract_request_data_filter, proxy_to_and_forward_response, Headers};

#[tokio::main]
async fn main() {
    let hello = warp::path!("hello" / String).map(|name| format!("Hello port, {}!", name));

    // // spawn base server
    tokio::spawn(warp::serve(hello).run(([0, 0, 0, 0], 8080)));

    let request_filter = extract_request_data_filter();
    let app = warp::path!("hello")
        // build the request with data from previous filters
        .and(request_filter)
        .and_then(|path, query, method, mut headers: Headers, mut body: Body| {
            headers
                .insert("FOO_HEADER", "Foo content".parse().unwrap())
                .unwrap();

            proxy_to_and_forward_response(
                "127.0.0.1".to_string(),
                "".to_string(),
                path,
                query,
                method,
                headers,
                body,
            )
        });

    // spawn proxy server
    warp::serve(app).run(([0, 0, 0, 0], 3030)).await;
}

You could also just compose with map whatever you need to modify after request_filter, something like (not tested):

request_filter.map(|(param, ..., headers, body)| {
    // modify whatever here and return all elements again
})

Hope this is enough, don't doubt on contact again if you need further help :D