Here's a Rust implementation of a basic reverse proxy using Hyper:
rust
use hyper::{Body, Client, Request, Response, Server, Uri, header};
use hyper::service::{make_service_fn, service_fn};
use hyper_tls::HttpsConnector;
use std::convert::Infallible;
use std::env;
use std::sync::Arc;
async fn proxy(
target_uri: Arc<Uri>,
client: Client<HttpsConnector<hyper::client::HttpConnector>, Body>,
req: Request<Body>,
) -> Result<Response<Body>, hyper::Error> {
// Extract path and query from incoming request
let incoming_path = req.uri().path_and_query().map_or("", |pq| pq.as_str());
// Construct full target URL
let full_url = format!("{}{}", target_uri, incoming_path);
let new_uri = match Uri::from_str(&full_url) {
Ok(u) => u,
Err(_) => return Ok(Response::builder()
.status(500)
.body(Body::from("Invalid URI"))
.unwrap()),
};
// Create new request with updated URI and headers
let (mut parts, body) = req.into_parts();
parts.uri = new_uri;
// Set Host header to target's host
if let Some(host) = target_uri.host() {
parts.headers.insert(
header::HOST,
HeaderValue::from_str(host).unwrap_or_else(|_| HeaderValue::from_static("localhost")),
);
}
let new_req = Request::from_parts(parts, body);
// Forward request to target server
client.request(new_req).await
}
#[tokio::main]
async fn main() {
// Get target URL from environment variable
let target_url = env::var("TARGET_URL").unwrap_or("http://example.com".to_string());
let target_uri: Uri = match target_url.parse() {
Ok(u) => u,
Err(e) => {
eprintln!("Invalid target URL: {e}");
return;
}
};
let target_uri = Arc::new(target_uri);
// Create HTTPS-enabled client
let https = HttpsConnector::new();
let client = Client::builder().build::<_, Body>(https);
// Setup server
let make_service = make_service_fn(move |_| {
let target_uri_cloned = Arc::clone(&target_uri);
let client_cloned = client.clone();
async move {
Ok::<_, Infallible>(service_fn(move |req| {
let target_uri = Arc::clone(&target_uri_cloned);
let client = client_cloned.clone();
proxy(target_uri, client, req)
}))
}
});
// Start listening on port 3000
let addr = ([0, 0, 0, 0], 3000).into();
if let Err(e) = Server::bind(&addr).serve(make_service).await {
eprintln!("Server error: {e}");
}
}
To use this proxy:
Set the target URL environment variable:
bash
export TARGET_URL=http://your-target-server.com
Run the proxy:
bash
cargo run
The proxy will listen on port 3000 and forward all requests to the specified target server. Key features:
Supports both HTTP and HTTPS destinations
Preserves request method, headers, and body
Handles host header correctly
Uses HTTPS for secure connections
Works with Tokio runtime for async handling
Note: This is a basic implementation. For production use, consider adding error handling, logging, and connection pooling. Also, for HTTPS requests, ensure the target server has proper certificates.