Use the `warp` or `axum` crate to serve static files from a directory in Rust. Add the dependency to your `Cargo.toml`, then configure the router to serve the `static` folder.
How to Serve Static Files in Rust
Use the warp or axum crate to serve static files from a directory in Rust. Add the dependency to your Cargo.toml, then configure the router to serve the static folder.
use warp::Filter;
#[tokio::main]
async fn main() {
let static_files = warp::fs::dir("static");
warp::serve(static_files).run(([127, 0, 0, 1], 3030)).await;
}
Add warp = "0.3" and tokio = { version = "1", features = ["full"] } to your Cargo.toml dependencies.
Serving static files in Rust sets up a web server that automatically sends files like images or CSS to a browser when requested. It works like a digital file cabinet where the server hands out specific documents based on the URL you type. You use this when building websites that need to load styles, scripts, or images alongside your main application logic.