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

Expose forward method #15

Closed danielSanchezQ closed 3 years ago

danielSanchezQ commented 4 years ago

In order to support more advanced composition for the forwarding addresses, the proxy_to_and_forward_response is exposed. This makes it easier to compose with other filters that would compute the proxy address. For example:

use warp::{hyper::body::Bytes, Filter, Rejection, Reply};
use warp_reverse_proxy::{
    extract_request_data_filter, proxy_to_and_forward_response, reverse_proxy_filter,
};

async fn log_response(response: http::Response<Bytes>) -> Result<impl Reply, Rejection> {
    println!("{:?}", response);
    Ok(response)
}

#[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" / String)
        .map(|port| (format!("http://127.0.0.1:{}/", port), "".to_string()))
        .untuple_one()
        .and(request_filter)
        .and_then(proxy_to_and_forward_response)
        .and_then(log_response);

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

This app uses the path to extract the port where to communicate with.

Implements #10

pukeko37 commented 3 years ago

This is a good solution to the issue I posted. I'm keen to see this merged into a new master version, soon.