靜態伺服器
將靜態檔案或內嵌檔案作為服務提供的中介軟體。具體 API 請查看文件。
應用場景
靜態檔案服務在 web 應用中有廣泛的應用場景:
- 提供網站的靜態資源如 CSS、JavaScript、圖片等檔案
- 託管單頁應用(SPA)
- 分發文件、媒體檔案、下載內容等
- 作為簡單網站的完整託管方案
主要功能
StaticDir
提供了對靜態本地資料夾的支援。可以將多個資料夾的列表作為參數。比如:
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;
}
如果在第一個資料夾中找不到對應的檔案,則會到第二個資料夾中尋找。
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 的優缺點
優點:
- 將靜態檔案編譯進二進位檔案中,簡化部署流程
- 無需在生產環境中單獨管理靜態檔案
- 可能獲得更好的效能(記憶體存取 vs 磁碟 I/O)
- 更安全,檔案不會被意外修改
缺點:
- 增加應用二進位檔案的大小
- 更新靜態內容需要重新編譯和部署整個應用
- 不適合頻繁變更的大型靜態內容
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;
}
可以通過 default 設定預設顯示頁面。with_fallback
和 fallback
可以設定在檔案找不到時,用這裡設定的檔案代替,這個對某些單頁網站應用來說還是有用的。