home ~ projects ~ socials

Serve A Local Directory With 404 Not Found Error Fallback With Rust's axum And tower-http

This is how I'm serving files from a directory on a local web server. The code also provides a custom 404 page not found fallback file.

```cargo
[dependencies]
axum = "0.7.5"
tokio = { version = "1.38.0", features = ["rt-multi-thread", "macros"] }
tower-http = { version = "0.5.2", features = ["fs"] }
```

use axum::Router;
use std::path::Path;
use tower_http::services::ServeDir;
use tower_http::services::ServeFile;

#[tokio::main]
async fn main() {
    let app = Router::new().nest_service(
        "/",
        ServeDir::new(Path::new("html"))
            .not_found_service(ServeFile::new(Path::new("html/404.html"))),
    );
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3434").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}
-- end of line --

References