Serving Static Files
1. Welcome and Icebreaker:
What’s the most creative static website or asset you’ve ever seen?
2. Outline the Session:
Agenda:
- Concept Explanation: How to serve static files in Axum using
tower_http. - Live Coding: Add static file serving to your app.
- Tasks: Practice by serving your own assets.
Learning Outcomes:
- Serve static files (HTML, CSS, JS, images) in Axum.
- Use
tower_http::services::ServeDirfor static assets.
Expectations: Try serving your own files and test with a browser!
3. Concept Explanation:
Static files are assets like HTML, CSS, JS, and images that don’t change dynamically. Axum can serve these using tower_http::services::ServeDir.
4. Live Coding Demonstration:
use axum::Router;
use tower_http::services::ServeDir;
#[tokio::main]
async fn main() {
let app = Router::new()
.nest_service("/static", ServeDir::new("./static"));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
Add tower-http = { version = "0.6", features = ["fs"] } to [dependencies] alongside Axum 0.8 and Tokio 1. Create static/style.css and request /static/style.css; unknown paths return 404.
Best Practices:
- Place static assets in a dedicated directory.
- Use proper cache headers for performance.
Common Pitfalls:
- Incorrect file paths or permissions.
- Not handling 404s for missing files.
5. Tasks
- Serve a custom HTML file from your static directory.
- Add a favicon and test it in your browser.
- Try serving large files and observe performance.