How to Build a Proxy Server in Rust

Web
Build a Rust proxy server by creating a binary crate with tokio and hyper dependencies to forward HTTP requests asynchronously.

You build a proxy server in Rust by creating a new binary crate, adding the tokio and hyper dependencies to Cargo.toml, and implementing an async handler that forwards incoming HTTP requests to a target server.

use hyper::{Body, Request, Response, Server};
use hyper::service::{make_service_fn, service_fn};
use std::net::SocketAddr;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let addr: SocketAddr = "127.0.0.1:8080".parse().unwrap();
    println!("Listening on http://{}", addr);

    let make_svc = make_service_fn(|_conn| async {
        Ok::<_, hyper::Error>(service_fn(|req: Request<Body>| async move {
            let client = hyper::Client::new();
            let target_url = format!("http://example.com{}", req.uri().path());
            let proxied_req = Request::builder()
                .method(req.method().clone())
                .uri(&target_url)
                .body(Body::empty())
                .unwrap();
            client.request(proxied_req).await
        }))
    });

    Server::bind(&addr).serve(make_svc).await?;

    Ok(())
}

Add tokio = { version = "1", features = ["full"] } and hyper = { version = "0.14", features = ["full"] } to your Cargo.toml before running.