Introduction

In case you ever need a blazingly fast HTTP-based file server in under 15 lines of code, here’s the best solution.

Prerequisite

Let's review the crates we will need for this use case:


[dependencies]
axum = "0.7.6"
axum-server = { version = "0.7.1", features = ["tls-rustls"] }
tower-http = { version = "0.6.1", features = ["fs"] }
tokio = { version = "=1.40.0", features = ["full"] }

We will use axum and axum-server, as the title suggests, as our backend framework. For serving the files we will use tower-http crate and non the less tokio for async.

Let's begin

main.rs


use std::net::SocketAddr;

use axum::Router;
use tower_http::services::ServeDir;

#[tokio::main]
async fn main() -> std::io::Result<()> {    
    let app = Router::new()
        .nest_service("/files/", ServeDir::new("/your/location"));

    let server = axum_server::bind(SocketAddr::from(([0, 0, 0, 0], 80)))
        .serve(app.into_make_service_with_connect_info::());

    server.await
}

This code sets up a simple, fast HTTP-based file server using the Axum framework and Tower HTTP's file-serving capability. It serves files from the specified directory (e.g., /your/location) when accessed via the /files/ route, and it listens on port 80 for incoming requests.