RustLabs-Workshop
RustLabs-Workshop copied to clipboard
Create an actix web server with or without SSL (RustTLS example)
//For non-production
#[cfg(debug_assertions)]
let addr: &str = "127.0.0.1";
//For production
#[cfg(not(debug_assertions))]
let addr: &str = "0.0.0.0";
//Rust TLS Config
let config = create_server_config();
//Json Configuration for Actix Web Server
let json_cfg = web::JsonConfig::default()
.limit(1024 * 1024 * 50);
let http_server = HttpServer::new(move || {
App::new()
.app_data(json_cfg.clone())
})
.bind((addr, 80))?
.workers(15) //some number of workers
.max_connections(1_024_000) //some amount of max connections
.max_connection_rate(10_240) //some number of new connections at a time
.run();
let https_server = HttpServer::new(move || {
App::new()
.app_data(json_cfg.clone())
})
.bind_rustls_0_22((addr, 443), config)?
.workers(15) //some number of workers
.max_connections(1_024_000) //some amount of max connections
.max_connection_rate(10_240) //some number of new connections at a time
.run();
//Code for SSL/TLS Server Configuration
pub fn create_server_config() -> ServerConfig {
let config = ServerConfig::builder()
.with_safe_defaults()
.with_no_client_auth();
// load TLS key/cert files
let cert_file = &mut BufReader::new(File::open("cert.pem").unwrap());
let key_file = &mut BufReader::new(File::open("key.pem").unwrap());
// convert files to key/cert objects
let cert_chain = certs(cert_file)
.unwrap()
.into_iter()
.map(Certificate)
.collect();
let mut keys: Vec<PrivateKey> = pkcs8_private_keys(key_file)
.unwrap()
.into_iter()
.map(PrivateKey)
.collect();
// exit if no keys could be parsed
if keys.is_empty() {
eprintln!("Could not locate PKCS 8 private keys.");
std::process::exit(1);
}
config.with_single_cert(cert_chain, keys.remove(0)).unwrap()
}