Clean up TLS example

This commit is contained in:
David Pedersen 2021-08-01 13:48:10 +02:00
parent ea82acd175
commit 593f3e115f

View file

@ -1,33 +1,25 @@
use std::fs::File; use axum::prelude::*;
use std::io::BufReader;
use std::sync::Arc;
use tokio_rustls::rustls::{
internal::pemfile::certs, internal::pemfile::pkcs8_private_keys, NoClientAuth, ServerConfig,
};
use tokio::net::TcpListener;
use tokio_rustls::TlsAcceptor;
use hyper::server::conn::Http; use hyper::server::conn::Http;
use hyper::{Body, Response}; use std::{fs::File, io::BufReader, sync::Arc};
use tokio::net::TcpListener;
use axum::handler::get; use tokio_rustls::{
use axum::route; rustls::{
internal::pemfile::certs, internal::pemfile::pkcs8_private_keys, NoClientAuth, ServerConfig,
},
TlsAcceptor,
};
#[tokio::main] #[tokio::main]
async fn main() { async fn main() {
let rustls_config = let rustls_config = rustls_server_config(
rustls_server_config("self_signed_certs/key.pem", "self_signed_certs/cert.pem"); "examples/self_signed_certs/key.pem",
"examples/self_signed_certs/cert.pem",
);
let acceptor = TlsAcceptor::from(rustls_config); let acceptor = TlsAcceptor::from(rustls_config);
let listener = TcpListener::bind("127.0.0.1:3443").await.unwrap(); let listener = TcpListener::bind("127.0.0.1:3000").await.unwrap();
let app = route( let app = route("/", get(handler));
"/",
get(|| async { Response::new(Body::from("Hello, world!")) }),
);
loop { loop {
let (stream, _addr) = listener.accept().await.unwrap(); let (stream, _addr) = listener.accept().await.unwrap();
@ -37,17 +29,16 @@ async fn main() {
tokio::spawn(async move { tokio::spawn(async move {
if let Ok(stream) = acceptor.accept(stream).await { if let Ok(stream) = acceptor.accept(stream).await {
let fut = Http::new().serve_connection(stream, app); Http::new().serve_connection(stream, app).await.unwrap();
match fut.await {
Ok(()) => (),
Err(_) => (),
}
} }
}); });
} }
} }
async fn handler() -> &'static str {
"Hello, World!"
}
fn rustls_server_config(key: &str, cert: &str) -> Arc<ServerConfig> { fn rustls_server_config(key: &str, cert: &str) -> Arc<ServerConfig> {
let mut config = ServerConfig::new(NoClientAuth::new()); let mut config = ServerConfig::new(NoClientAuth::new());