Serve Static

將靜態文件或者內嵌的文件作爲服務提供的中間件.

主要功能

  • StaticDir 提供了對靜態本地文件夾的支持. 可以將多個文件夾的列表作爲參數. 比如:

    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"

    如果在第一個文件夾中找不到對應的文件, 則會到第二個文件夾中找.

    StaticDir 支持在存在壓縮文件的情況下,優先發送壓縮文件。比如存在 index.html, index.html.gz, index.html.zst, index.html.br 這幾個文件,則 index.html.gz, index.html.zst, index.html.br 被認爲是 index.html 的預壓縮版本,會根據請求信息,發送對應的壓縮文件。

  • 提供了對 rust-embed 的支持, 比如:

    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 可以設置在文件找不到時, 用這裏設置的文件代替, 這個對應某些單頁網站應用來還是有用的.