Serve Static

Middleware that provides static files or embedded files as services.

Main Features

  • StaticDir provides support for static local folders. You can take a list of multiple folders as an argument. For example:

    use salvo::prelude::*;
    use salvo::serve_static::StaticDir;
    
    #[tokio::main]
    async fn main() {
        tracing_subscriber::fmt().init();
    
        let router = Router::with_path("<**path>").get(
            StaticDir::new([
                "examples/static-dir-list/static/boy",
                "examples/static-dir-list/static/girl",
            ])
            .defaults("index.html")
            .auto_list(true),
        );
    
        let acceptor = TcpListener::new("127.0.0.1:5800").bind().await;
        Server::new(acceptor).serve(router).await;
    }
    [package]
    name = "example-static-dir-list"
    version = "0.1.0"
    edition = "2021"
    publish = false
    
    
    [dependencies]
    salvo = { workspace = true, features = ["serve-static"] }
    tokio = { version = "1", features = ["macros"] }
    tracing = "0.1"
    tracing-subscriber = "0.3"

    If the corresponding file is not found in the first folder, it will look in the second folder.

    StaticDir supports sending compressed files first when compressed files exist. For example, if there are files index.html, index.html.gz, index.html.zst, index.html.br, then index.html.gz, index.html. zst, index.html.br are considered to be pre-compressed versions of index.html, and the corresponding compressed files will be sent according to the request information.

  • Provides support for rust-embed, such as:

    use rust_embed::RustEmbed;
    use salvo::prelude::*;
    use salvo::serve_static::static_embed;
    
    #[derive(RustEmbed)]
    #[folder = "static"]
    struct Assets;
    
    #[tokio::main]
    async fn main() {
        tracing_subscriber::fmt().init();
    
        let router = Router::with_path("<**path>").get(static_embed::<Assets>().fallback("index.html"));
    
        let acceptor = TcpListener::new("127.0.0.1:5800").bind().await;
        Server::new(acceptor).serve(router).await;
    }
    [package]
    name = "example-static-embed-files"
    version = "0.1.0"
    edition = "2021"
    publish = false
    
    
    [dependencies]
    rust-embed = { workspace = true }
    salvo = { workspace = true, features = ["serve-static"] }
    tokio = { version = "1", features = ["macros"] }
    tracing = "0.1"
    tracing-subscriber = "0.3"

    with_fallback can be set to replace the file set here when the file is not found, which is useful for some single-page website applications.