Static Server

Middleware that serves static files or embedded files. For detailed API, please view the documentation.

Use Cases

Static file servers have a wide range of applications in web development:

  • Serving static resources for websites, such as CSS, JavaScript, images, etc.
  • Hosting Single Page Applications (SPAs)
  • Distributing documents, media files, downloadable content, etc.
  • Serving as a complete hosting solution for simple websites

Main Features

  • StaticDir provides support for serving static files from local directories. It can accept a list of multiple directories as parameters. For example:
main.rs
Cargo.toml
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([
            "static-dir-list/static/boy",
            "static-dir-list/static/girl",
            "static/boy",
            "static/girl",
        ])
        .include_dot_files(false)
        .defaults("index.html")
        .auto_list(true),
    );

    let acceptor = TcpListener::new("0.0.0.0:8698").bind().await;
    Server::new(acceptor).serve(router).await;
}

If a file is not found in the first directory, it will be searched for in the second directory.

StaticDir supports serving pre-compressed files when available. For example, if files like index.html, index.html.gz, index.html.zst, and index.html.br exist, then index.html.gz, index.html.zst, and index.html.br are considered pre-compressed versions of index.html. The appropriate compressed file will be served based on the request information.

  • Provides support for rust-embed. For example:

Pros and Cons of rust-embed

Pros:

  • Compiles static files into the binary, simplifying deployment.
  • No need to manage static files separately in production environments.
  • Potentially better performance (memory access vs. disk I/O).
  • Enhanced security, as files cannot be accidentally modified.

Cons:

  • Increases the size of the application binary.
  • Updating static content requires recompiling and redeploying the entire application.
  • Not suitable for large static content that changes frequently.
main.rs
Cargo.toml
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("0.0.0.0:8698").bind().await;
    Server::new(acceptor).serve(router).await;
}

You can set a default page to display using the default option. The with_fallback and fallback methods allow you to specify a fallback file to serve when a requested file is not found, which is useful for certain single-page website applications.