1
0
mirror of https://github.com/actix/actix-website synced 2025-06-27 07:29:02 +02:00

docs: use rustls in http/2 example

This commit is contained in:
Rob Ede
2024-03-02 17:30:54 +00:00
parent 7c063e890f
commit 2f9e49c622
4 changed files with 29 additions and 19 deletions

View File

@ -4,6 +4,9 @@ version = "1.0.0"
publish = false
edition.workspace = true
# <deps>
[dependencies]
actix-web = { version = "4", features = ["openssl"] }
openssl = { version = "0.10", features = ["v110"] }
actix-web = { version = "4", features = ["rustls-0_22"] }
rustls = "0.22"
rustls-pemfile = "2"
# </deps>

View File

@ -1,24 +1,36 @@
use std::{fs::File, io::BufReader};
// <main>
use actix_web::{web, App, HttpRequest, HttpServer, Responder};
use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod};
async fn index(_req: HttpRequest) -> impl Responder {
"Hello."
"Hello TLS World!"
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
// load TLS keys
let mut certs_file = BufReader::new(File::open("cert.pem").unwrap());
let mut key_file = BufReader::new(File::open("key.pem").unwrap());
// load TLS certs and key
// to create a self-signed temporary cert for testing:
// `openssl req -x509 -newkey rsa:4096 -nodes -keyout key.pem -out cert.pem -days 365 -subj '/CN=localhost'`
let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
builder
.set_private_key_file("key.pem", SslFiletype::PEM)
let tls_certs = rustls_pemfile::certs(&mut certs_file)
.collect::<Result<Vec<_>, _>>()
.unwrap();
let tls_key = rustls_pemfile::pkcs8_private_keys(&mut key_file)
.next()
.unwrap()
.unwrap();
// set up TLS config options
let tls_config = rustls::ServerConfig::builder()
.with_no_client_auth()
.with_single_cert(tls_certs, rustls::pki_types::PrivateKeyDer::Pkcs8(tls_key))
.unwrap();
builder.set_certificate_chain_file("cert.pem").unwrap();
HttpServer::new(|| App::new().route("/", web::get().to(index)))
.bind_openssl("127.0.0.1:8080", builder)?
.bind_rustls_0_22(("127.0.0.1", 8443), tls_config)?
.run()
.await
}