強制 HTTPS

force-https 中介軟體能夠強制所有請求轉向使用 HTTPS 通訊協定。

若將此中介軟體應用於 Router,僅在路由匹配成功時才會強制轉換通訊協定;若遇到頁面不存在的情況,則不會進行轉向。

然而更常見的需求是希望所有請求都能自動轉向,即使在路由未能匹配而返回 404 錯誤時亦然。此時可將中介軟體添加至 Service 層級。無論請求是否成功匹配路由,添加於 Service 的中介軟體皆會執行。

範例程式碼

main.rs
Cargo.toml
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:8698"))
        .bind()
        .await;
    Server::new(acceptor).serve(service).await;
}