added https support

This commit is contained in:
2024-12-10 16:29:52 -08:00
parent 1227a935a2
commit 7573478287
4 changed files with 499 additions and 1 deletions

View File

@ -7,6 +7,12 @@ use std::{
thread,
};
#[cfg(feature = "https")]
use rustls::{
pki_types::{pem::PemObject, CertificateDer, PrivateKeyDer},
ServerConfig, ServerConnection,
};
use crate::{
http::{request::RequestLine, Request, Response},
Client,
@ -16,6 +22,9 @@ pub struct Server {
listener: TcpListener,
on_request: Arc<Mutex<Option<Box<dyn Fn(Request) -> Response + Send + 'static>>>>,
#[cfg(feature = "https")]
tls_config: Option<Arc<ServerConfig>>,
}
impl Server {
@ -27,6 +36,9 @@ impl Server {
listener,
on_request: Arc::new(Mutex::new(None)),
#[cfg(feature = "https")]
tls_config: None,
}
}
@ -36,7 +48,15 @@ impl Server {
let on_request = Arc::clone(&self.on_request);
#[cfg(feature = "https")]
let tls_config = self.tls_config.clone().unwrap();
thread::spawn(move || {
#[cfg(feature = "https")]
let connection = ServerConnection::new(tls_config).unwrap();
#[cfg(feature = "https")]
let stream = rustls::StreamOwned::new(connection, stream);
let mut client = Client::new(stream);
let mut buffer = vec![0; 1024];
@ -82,7 +102,7 @@ impl Server {
if let Some(content) = response.content {
client.write(b"\r\n").unwrap();
client.write(&content).unwrap();
client.write_all(&content).unwrap();
} else {
client.write(b"\r\n").unwrap();
}
@ -96,6 +116,25 @@ impl Server {
}
}
#[cfg(feature = "https")]
pub fn with_https(mut self, cert_file: &str, key_file: &str) -> Self {
let certs = CertificateDer::pem_file_iter(cert_file)
.unwrap()
.map(|cert| cert.unwrap())
.collect::<Vec<_>>();
let key = PrivateKeyDer::from_pem_file(key_file).unwrap();
let config = ServerConfig::builder()
.with_no_client_auth()
.with_single_cert(certs, key)
.unwrap();
self.tls_config = Some(Arc::new(config));
self
}
pub fn on_request<F>(&mut self, f: F)
where
F: Fn(Request) -> Response + Send + 'static,