Static Server
Middleware for serving static files or embedded files. For detailed API, please refer to the documentation.
Use Cases
Static file serving has wide applications in web development:
- Serving static assets for websites, such as CSS, JavaScript, and image files.
- Hosting Single Page Applications (SPAs).
- Distributing documents, media files, downloadable content, etc.
- Acting as a complete hosting solution for simple websites.
Key Features
StaticDir
provides support for serving static files from local directories. You can pass a list of multiple directories as arguments. For example:
static-dir-list/src/main.rs
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:5800").bind().await;
Server::new(acceptor).serve(router).await;
}
If a corresponding file is not found in the first directory, it will be searched for in the second directory.
StaticDir
supports prioritizing sending pre-compressed files if they exist. For instance, if index.html
, index.html.gz
, index.html.zst
, and index.html.br
all 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 sent based on the request information (e.g., Accept-Encoding
header).
- Provides support for
rust-embed
, for example:
Pros and Cons ofrust-embed
Pros:
- Embeds static files directly into the binary, simplifying the deployment process.
- Eliminates the need to manage static files separately in the production environment.
- Potentially offers better performance (memory access vs. disk I/O).
- More secure, 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 assets that change frequently.
static-embed-files/src/main.rs
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:5800").bind().await;
Server::new(acceptor).serve(router).await;
}
You can set a default page using default
. The with_fallback
and fallback
options allow you to specify a file to serve when the requested file is not found. This is particularly useful for certain Single Page Applications (SPAs).