Skip to content
Myr

main.rs

This file

Path

examples/tls-rustls/src/main.rs

101 lines · 2.8 KiB · Rust

Last changed by

Accept owned locations in Redirect constructors (#3635)Joey de Waalbefore adoption7961711

History of this file

Take it

1//! Run with2//!3//! ```not_rust4//! cargo run -p example-tls-rustls5//! ```67#![allow(unused_imports)]89use axum::{10    handler::HandlerWithoutStateExt,11    http::{uri::Authority, StatusCode, Uri},12    response::Redirect,13    routing::get,14    BoxError, Router,15};16use axum_server::tls_rustls::RustlsConfig;17use std::{net::SocketAddr, path::PathBuf};18use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};1920#[allow(dead_code)]21#[derive(Clone, Copy)]22struct Ports {23    http: u16,24    https: u16,25}2627#[tokio::main]28async fn main() {29    tracing_subscriber::registry()30        .with(31            tracing_subscriber::EnvFilter::try_from_default_env()32                .unwrap_or_else(|_| format!("{}=debug", env!("CARGO_CRATE_NAME")).into()),33        )34        .with(tracing_subscriber::fmt::layer())35        .init();3637    let ports = Ports {38        http: 7878,39        https: 3000,40    };41    // optional: spawn a second server to redirect http requests to this server42    tokio::spawn(redirect_http_to_https(ports));4344    // configure certificate and private key used by https45    let config = RustlsConfig::from_pem_file(46        PathBuf::from(env!("CARGO_MANIFEST_DIR"))47            .join("self_signed_certs")48            .join("cert.pem"),49        PathBuf::from(env!("CARGO_MANIFEST_DIR"))50            .join("self_signed_certs")51            .join("key.pem"),52    )53    .await54    .unwrap();5556    let app = Router::new().route("/", get(handler));5758    // run https server59    let addr = SocketAddr::from(([127, 0, 0, 1], ports.https));60    tracing::debug!("listening on {}", addr);61    axum_server::bind_rustls(addr, config)62        .serve(app.into_make_service())63        .await64        .unwrap();65}6667#[allow(dead_code)]68async fn handler() -> &'static str {69    "Hello, World!"70}7172#[allow(dead_code)]73async fn redirect_http_to_https(ports: Ports) {74    fn make_https(uri: Uri, https_port: u16) -> Result<Uri, BoxError> {75        let mut parts = uri.into_parts();7677        parts.scheme = Some(axum::http::uri::Scheme::HTTPS);78        parts.authority = Some(format!("localhost:{https_port}").parse()?);7980        if parts.path_and_query.is_none() {81            parts.path_and_query = Some("/".parse().unwrap());82        }8384        Ok(Uri::from_parts(parts)?)85    }8687    let redirect = move |uri: Uri| async move {88        match make_https(uri, ports.https) {89            Ok(uri) => Ok(Redirect::permanent(uri.to_string())),90            Err(error) => {91                tracing::warn!(%error, "failed to convert URI to HTTPS");92                Err(StatusCode::BAD_REQUEST)93            }94        }95    };9697    let addr = SocketAddr::from(([127, 0, 0, 1], ports.http));98    let listener = tokio::net::TcpListener::bind(addr).await.unwrap();99    tracing::debug!("listening on {}", listener.local_addr().unwrap());100    axum::serve(listener, redirect.into_make_service()).await;101}