http_and_https/
http_and_https.rs

1//! Run with `cargo run --all-features --example http_and_https` command.
2//!
3//! To connect through browser, navigate to "http://localhost:3000" url which should redirect to
4//! "https://localhost:3443".
5
6use axum::{http::uri::Uri, response::Redirect, routing::get, Router};
7use hyper_serve::tls_rustls::RustlsConfig;
8use std::net::SocketAddr;
9
10#[tokio::main]
11async fn main() {
12    let http = tokio::spawn(http_server());
13    let https = tokio::spawn(https_server());
14
15    // Ignore errors.
16    let _ = tokio::join!(http, https);
17}
18
19async fn http_server() {
20    let app = Router::new().route("/", get(http_handler));
21
22    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
23    println!("http listening on {}", addr);
24    hyper_serve::bind(addr)
25        .serve(app.into_make_service())
26        .await
27        .unwrap();
28}
29
30async fn http_handler(uri: Uri) -> Redirect {
31    let uri = format!("https://127.0.0.1:3443{}", uri.path());
32
33    Redirect::temporary(&uri)
34}
35
36async fn https_server() {
37    let app = Router::new().route("/", get(|| async { "Hello, world!" }));
38
39    let config = RustlsConfig::from_pem_file(
40        "examples/self-signed-certs/cert.pem",
41        "examples/self-signed-certs/key.pem",
42    )
43    .await
44    .unwrap();
45
46    let addr = SocketAddr::from(([127, 0, 0, 1], 3443));
47    println!("https listening on {}", addr);
48    hyper_serve::bind_rustls(addr, config)
49        .serve(app.into_make_service())
50        .await
51        .unwrap();
52}