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