Designing a reverse proxy in Rust
The user wants a high-performance reverse proxy in Rust for serving static files. I need to distinguish between a typical static file server and a reverse proxy that might serve as a front for another static file server (like S3 or Nginx). The wording suggests it could either read from a local file system or proxy requests. I should create a solution using frameworks like tokio and hyper, prioritizing direct use of hyper for better performance and considering zero-copy techniques.Thinking through Rust implementation
Creating a high-performance reverse proxy in Rust isn't straightforward, especially with sendfile and using tokio. I can leverage tokio::fs and use hyper::Body::from or perhaps Body::wrap_stream for handling static files, as filesystem I/O is essential for performance. Hyper suits a low-level implementation, while I might consider connection pooling with HTTP/1.1 and HTTP/2 support. The user wants a main.rs file with a complete code solution, including dependencies in Cargo.toml, and brief instructions for building and running.Creating a reverse proxy example
I need to create an example that listens on port 8080 (which should be configurable). If a file exists in a local directory (like ./static), I can serve it using tokio::fs::File and hyper::Body. If the file doesn't exist, I’ll proxy the request to an upstream server, potentially set in an environment variable. The user’s request is a bit ambiguous, but it’s clear they want both functionalities, even if that means a bit more code. Still, the focus should be on serving static files.Planning the Rust server functionality
The user wants a Rust server that simply forwards requests but focuses on serving static files efficiently. To implement best practices, using sendfile could be ideal, though it's complex. A straightforward approach would be to create a Rust project with a hyper server that has two modes: if the path matches /static or a file exists in the configured directory, it will serve from the disk; otherwise, it forwards the request to the upstream server. I think caching can be skipped for simplicity, but I still ponder what "high-performance" truly means.Developing comprehensive static file handling and proxying
The goal is to create a Rust reverse proxy server that supports GET and HEAD requests while efficiently handling static file serving. When an incoming request matches the static file route, I need to serve it from disk or proxy to an upstream server. This will involve rewriting the request URI and adjusting headers according to best practices, like removing unnecessary ones. I'll ensure security by sanitizing file paths and using asynchronous file handling with tokio. The implementation will leverage hyper's capabilities for error handling and streaming responses efficiently.Implementing a high-performance reverse proxy in Rust
I need to develop a Rust reverse proxy that serves static files and proxies other requests. First, I’ll handle hop-by-hop headers to ensure compliance with best practices. The server will check if a static file exists; if yes, serve it otherwise, proxy the request to the upstream server. I’ll configure dependencies, ensure the handling of errors, and simplify implementations with features from hyper and tokio. Additionally, I’ll provide a clear example and a brief explanation, emphasizing the potential for further enhancements like caching and TLS for production use.Clarifying HTTP/1 and HTTP/2 without TLS
I'm working on a server that supports HTTP but isn't using TLS. The default builder uses HTTP/1, which is fine for our purposes. While I could set it up for HTTP/2, that’s uncommon without TLS, so I’ll stick with HTTP/1 and focus on performance aspects like asynchronous handling and connection pooling.
I need to ensure proper imports in the code, especially for aspects like make_service_fn from hyper. My implementation will read configuration variables for directories. Let’s piece together the main components in a concise way while ensuring error handling for server responses, so I keep everything straightforward and effective!Implementing server functionality
I’m figuring out the server logic, and it seems I can handle the metadata checks effectively. When checking if the file path refers to a directory, I’ll make a note to not reassign filepath directly — instead, I’ll use a mutable variable.
Also, for handling requests, I should differentiate between HEAD and GET requests by setting Content-Length appropriately and considering caching headers for performance. I’ve also noted that error handling should reflect any IO issues.
Next, I’m organizing utility functions and ensuring I import necessary modules to streamline the code!Setting up the server
I'm working on the server setup. The main function needs the binding address and upstream URI from environment variables. I’ll ensure that the upstream URI has the correct scheme and authority.
I’m also defining the proxy_or_static function that lets the server decide whether to serve static files or proxy requests. Additionally, I'm implementing function definitions like try_serve_static, internal_server_error, and bad_gateway.
Oh! And I’ll double-check all imports and ensure the final code is prepared for deployment, especially regarding clarity for users who may want a static-only setup.Final considerations for server setup
I need to mention the environment variables: BIND_ADDR, UPSTREAM, and STATIC_DIR in my explanation. I plan to keep the narrative brief, likely one or two paragraphs, plus some code.
It's important to highlight that I'm using hyper and tokio for asynchronous zero-copy streaming. If the user has additional feature requests later, I'll be ready, but that's not the focus right now. I’ll double-check that the necessary features for hyper 0.14 are included. Alright, let’s produce the final answer! Below is a minimal but high‑performance reverse proxy in Rust, built on tokio + hyper, that:
- Serves static files from a local directory (asynchronously, streaming large files).
- Falls back to proxying the request to an upstream server if the file is not found.
You can easily strip out the static part if you want a pure reverse proxy.
Cargo.toml
[package]
name = "static_reverse_proxy"
version = "0.1.0"
edition = "2021"
[dependencies]
tokio = { version = "1", features = ["full"] }
hyper = { version = "0.14", features = ["full"] }
tokio-util = { version = "0.7", features = ["io"] }
mime_guess = "2.0"
src/main.rs
use std::{
convert::Infallible,
env,
io,
net::SocketAddr,
path::{Path, PathBuf},
sync::Arc,
time::Duration,
};
use hyper::{
client::HttpConnector,
header::{
HeaderMap, HeaderName, HeaderValue, CONNECTION, HOST, PROXY_AUTHENTICATE,
PROXY_AUTHORIZATION, TE, TRAILER, TRANSFER_ENCODING, UPGRADE,
},
service::{make_service_fn, service_fn},
Body, Client, Method, Request, Response, Server, StatusCode, Uri,
};
use tokio::fs::File;
use tokio_util::io::ReaderStream;
fn resolve_path(static_dir: &Path, uri_path: &str) -> Option<PathBuf> {
use std::path::Component;
// Remove the leading slash
let rel = uri_path.trim_start_matches('/');
// Map "/" to "index.html"
let rel = if rel.is_empty() { "index.html" } else { rel };
let mut path = PathBuf::from(static_dir);
for comp in Path::new(rel).components() {
match comp {
Component::Normal(part) => path.push(part),
Component::CurDir => {}
// Disallow any attempt to escape the static directory
Component::RootDir | Component::Prefix(_) | Component::ParentDir => {
return None;
}
}
}
Some(path)
}
async fn try_serve_static(
req: &Request<Body>,
static_dir: &Path,
) -> io::Result<Option<Response<Body>>> {
// Only serve GET/HEAD from disk
if req.method() != Method::GET && req.method() != Method::HEAD {
return Ok(None);
}
let path = req.uri().path();
let file_path = match resolve_path(static_dir, path) {
Some(p) => p,
None => return Ok(None),
};
let meta = match tokio::fs::metadata(&file_path).await {
Ok(m) => m,
Err(e) => {
if e.kind() == io::ErrorKind::NotFound {
return Ok(None); // Not a static file, let proxy handle it
} else {
return Err(e);
}
}
};
if !meta.is_file() {
return Ok(None);
}
let mime = mime_guess::from_path(&file_path).first_or_octet_stream();
let len = meta.len();
let mut builder = Response::builder()
.status(StatusCode::OK)
.header("Content-Type", mime.as_ref())
.header("Content-Length", len.to_string());
// HEAD: headers only, no body
if req.method() == Method::HEAD {
let resp = builder
.body(Body::empty())
.expect("failed to build HEAD response");
return Ok(Some(resp));
}
// GET: stream file asynchronously
let file = File::open(file_path).await?;
let stream = ReaderStream::new(file);
let body = Body::wrap_stream(stream);
let resp = builder
.body(body)
.expect("failed to build GET response");
Ok(Some(resp))
}
fn strip_hop_by_hop_headers(headers: &mut HeaderMap<HeaderValue>) {
// Remove headers referenced in the `Connection` header
if let Some(conn_val) = headers.get(CONNECTION).cloned() {
if let Ok(conn_str) = conn_val.to_str() {
for name in conn_str.split(',') {
if let Ok(name) = name.trim().parse::<HeaderName>() {
headers.remove(name);
}
}
}
}
// Standard hop-by-hop headers
headers.remove(CONNECTION);
headers.remove(PROXY_AUTHENTICATE);
headers.remove(PROXY_AUTHORIZATION);
headers.remove(TE);
headers.remove(TRAILER);
headers.remove(TRANSFER_ENCODING);
headers.remove(UPGRADE);
}
fn build_upstream_uri(orig: &Uri, upstream: &Uri) -> Result<Uri, hyper::http::Error> {
let mut parts = orig.clone().into_parts();
parts.scheme = upstream.scheme().cloned();
parts.authority = upstream.authority().cloned();
Uri::from_parts(parts)
}
fn internal_server_error() -> Response<Body> {
Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
.body(Body::from("Internal Server Error"))
.unwrap()
}
fn bad_gateway() -> Response<Body> {
Response::builder()
.status(StatusCode::BAD_GATEWAY)
.body(Body::from("Bad Gateway"))
.unwrap()
}
async fn proxy_or_static(
mut req: Request<Body>,
client: Client<HttpConnector, Body>,
upstream: Uri,
static_dir: Arc<PathBuf>,
) -> Result<Response<Body>, Infallible> {
// First, attempt to serve from disk
match try_serve_static(&req, &static_dir).await {
Ok(Some(resp)) => return Ok(resp),
Ok(None) => {
// Not a local file, fall through to proxy
}
Err(err) => {
eprintln!("Error serving static file: {}", err);
return Ok(internal_server_error());
}
}
// Proxy to upstream
let new_uri = match build_upstream_uri(req.uri(), &upstream) {
Ok(u) => u,
Err(err) => {
eprintln!("Error building upstream URI: {}", err);
return Ok(internal_server_error());
}
};
*req.uri_mut() = new_uri;
// Clean hop-by-hop headers and set Host for upstream
strip_hop_by_hop_headers(req.headers_mut());
if let Some(auth) = upstream.authority() {
if let Ok(value) = HeaderValue::from_str(auth.as_str()) {
req.headers_mut().insert(HOST, value);
}
}
match client.request(req).await {
Ok(mut resp) => {
// Strip hop-by-hop headers from the response as well
strip_hop_by_hop_headers(resp.headers_mut());
Ok(resp)
}
Err(err) => {
eprintln!("Upstream request failed: {}", err);
Ok(bad_gateway())
}
}
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
// Bind address, e.g. "0.0.0.0:8080"
let bind_addr = env::var("BIND_ADDR").unwrap_or_else(|_| "0.0.0.0:8080".to_string());
let addr: SocketAddr = bind_addr.parse()?;
// Upstream origin, e.g. "http://127.0.0.1:8000"
let upstream = env::var("UPSTREAM").unwrap_or_else(|_| "http://127.0.0.1:8000".to_string());
let upstream_uri: Uri = upstream.parse()?;
if upstream_uri.scheme().is_none() || upstream_uri.authority().is_none() {
return Err("UPSTREAM must include scheme and host, e.g. http://127.0.0.1:8000".into());
}
// Directory with static files
let static_dir_str = env::var("STATIC_DIR").unwrap_or_else(|_| "./static".to_string());
let static_dir = Arc::new(PathBuf::from(static_dir_str));
// Pooled, keep‑alive HTTP client for upstream
let client: Client<HttpConnector, Body> = Client::builder()
.pool_max_idle_per_host(64)
.pool_idle_timeout(Duration::from_secs(90))
.build_http();
let make_svc = make_service_fn(move |_conn| {
let client = client.clone();
let upstream_uri = upstream_uri.clone();
let static_dir = static_dir.clone();
async move {
Ok::<_, Infallible>(service_fn(move |req| {
proxy_or_static(req, client.clone(), upstream_uri.clone(), static_dir.clone())
}))
}
});
let server = Server::bind(&addr).serve(make_svc);
println!("Listening on http://{}", addr);
println!("Serving static files from: {:?}", static_dir);
println!("Proxying to upstream: {}", upstream_uri);
server.await?;
Ok(())
}
Usage
Build and run:
cargo run --release
Config via environment variables:
BIND_ADDR – default 0.0.0.0:8080
STATIC_DIR – default ./static
UPSTREAM – default http://127.0.0.1:8000
Example:
BIND_ADDR=0.0.0.0:8080 \
STATIC_DIR=./public \
UPSTREAM=http://127.0.0.1:9000 \
cargo run --release
This design is fully async, streams large files, reuses connections to the upstream, and strips hop‑by‑hop headers as a proper reverse proxy. If you want a pure reverse proxy (no local static files), just remove the try_serve_static call and related code.