rustls_reload/
rustls_reload.rs

1//! Run with `cargo run --all-features --example rustls_reload` command.
2//!
3//! To connect through browser, navigate to "https://localhost:3000" url.
4//!
5//! Certificate common name will be "localhost".
6//!
7//! After 20 seconds, certificate common name will be "reloaded".
8
9use axum::{routing::get, Router};
10use hyper_serve::tls_rustls::RustlsConfig;
11use std::{net::SocketAddr, time::Duration};
12use tokio::time::sleep;
13
14#[tokio::main]
15async fn main() {
16    let app = Router::new().route("/", get(|| async { "Hello, world!" }));
17
18    let config = RustlsConfig::from_pem_file(
19        "examples/self-signed-certs/cert.pem",
20        "examples/self-signed-certs/key.pem",
21    )
22    .await
23    .unwrap();
24
25    // Spawn a task to reload tls.
26    tokio::spawn(reload(config.clone()));
27
28    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
29    println!("listening on {}", addr);
30    hyper_serve::bind_rustls(addr, config)
31        .serve(app.into_make_service())
32        .await
33        .unwrap();
34}
35
36async fn reload(config: RustlsConfig) {
37    // Wait for 20 seconds.
38    sleep(Duration::from_secs(20)).await;
39
40    println!("reloading rustls configuration");
41
42    // Reload rustls configuration from new files.
43    config
44        .reload_from_pem_file(
45            "examples/self-signed-certs/reload/cert.pem",
46            "examples/self-signed-certs/reload/key.pem",
47        )
48        .await
49        .unwrap();
50
51    println!("rustls configuration reloaded");
52}