Force HTTPS
force-https
中間件可以強製所有的請求轉嚮至使用 HTTPS 協議.
此中間價如果應用於 Router
則隻有在路由匹配到時才會強製轉換協議,如果遇到頁麵不存在的情況,則不會轉嚮.
但更常見的需求是期望任何的請求都自動轉嚮,即使在路由未能匹配,返回 404
錯誤時,這時候可以把中間件添加到 Service
上. 不管請求是否被路由成功匹配, Service
上添加的中間件總是會執行.
示例代碼
use salvo::conn::rustls::{Keycert, RustlsConfig};
use salvo::prelude::*;
#[handler]
async fn hello() -> &'static str {
"Hello World"
}
#[tokio::main]
async fn main() {
tracing_subscriber::fmt().init();
let router = Router::new().get(hello);
let service = Service::new(router).hoop(ForceHttps::new().https_port(5443));
let config = RustlsConfig::new(
Keycert::new()
.cert(include_bytes!("../certs/cert.pem").as_ref())
.key(include_bytes!("../certs/key.pem").as_ref()),
);
let acceptor = TcpListener::new("0.0.0.0:5443")
.rustls(config)
.join(TcpListener::new("0.0.0.0:5800"))
.bind()
.await;
Server::new(acceptor).serve(service).await;
}
[package]
name = "example-force-https"
version.workspace = true
edition.workspace = true
publish.workspace = true
[dependencies]
salvo = { workspace = true, features = ["rustls", "force-https"] }
tokio = { workspace = true, features = ["macros"] }
tracing.workspace = true
tracing-subscriber.workspace = true