expression
Axum: expose a single static file
ServeFile maps a route to one selected file. This example creates a fixed public asset inside a fresh scratch directory and exposes it at a single route. This is not a dynamic download handler or authorization check. Standalone Cargo example: execute only in a fresh isolated scratch directory. Expected stdout (not executed): 200 About Common mistake: Building ServeFile from an arbitrary user-provided path.
Formal Syntax & Structure
rust syntaxrust
Router::new().route_service("/about.txt", ServeFile::new(path))Working Example
Example Snippetrust
use axum::{Router, body::{Body, to_bytes}, http::{Request, StatusCode}};use tower::ServiceExt;
#[tokio::main(flavor = "current_thread")]async fn main() { use tower_http::services::ServeFile; std::fs::create_dir("v73-single-demo").unwrap(); std::fs::write("v73-single-demo/about.txt", "About").unwrap(); let app = Router::new().route_service("/about.txt", ServeFile::new("v73-single-demo/about.txt")); let r = app.oneshot(Request::builder().uri("/about.txt").body(Body::empty()).unwrap()).await.unwrap(); println!("{}", r.status().as_u16()); println!("{}", String::from_utf8_lossy(&to_bytes(r.into_body(), 64).await.unwrap()));}