Serve Static
将静态文件或者内嵌的文件作为服务提供的中间件. 具体 API 请查看文档.
主要功能
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"
可以通过 default 设置默认显示页面. with_fallback
和 fallback
可以设置在文件找不到时, 用这里设置的文件代替, 这个对应某些单页网站应用来还是有用的.