Let me help write a basic HTTP proxy server in Rust. This will forward HTTP requests while allowing you to inspect and modify traffic - useful for debugging, testing, and learning about web protocols.
rust
use tokio::{net::TcpListener, io::{AsyncReadExt, AsyncWriteExt}};
use hyper::{Client, Request, Body};
use std::convert::TryFrom;
use std::net::SocketAddr;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Listen on localhost:8080
let listener = TcpListener::bind("127.0.0.1:8080").await?;
println!("Proxy server running on http://127.0.0.1:8080");
// Accept incoming connections
while let Ok((mut client_conn, _)) = listener.accept().await {
tokio::spawn(async move {
let mut buf = vec![0; 4096];
// Read the incoming request
match client_conn.read(&mut buf).await {
Ok(n) => {
let request = String::from_utf8_lossy(&buf[..n]);
// Parse the request
if let Ok(mut req) = Request::try_from(request.as_bytes()) {
// Create HTTP client
let client = Client::new();
// Forward the request and get response
if let Ok(resp) = client.request(req).await {
// Convert response to bytes
let body_bytes = hyper::body::to_bytes(resp.into_body()).await.unwrap();
// Send response back to client
if let Err(e) = client_conn.write_all(&body_bytes).await {
eprintln!("Failed to write response: {}", e);
}
}
}
}
Err(e) => eprintln!("Failed to read from connection: {}", e),
}
});
}
Ok(())
}
This is a basic implementation that:
Creates a TCP listener on port 8080
Accepts incoming connections
Reads the HTTP request
Forwards it to the destination server
Returns the response to the client
To use this code, you'll need these dependencies in your Cargo.toml:
toml
[dependencies]
tokio = { version = "1.0", features = ["full"] }
hyper = { version = "0.14", features = ["full"] }
Some important notes:
This is a basic implementation and doesn't handle HTTPS
Error handling is minimal
No request/response modification is implemented
No logging or monitoring included
Would you like me to add any specific features like HTTPS support, request logging, or request modification capabilities?