Skip to content

Instantly share code, notes, and snippets.

@allencamal
Last active April 11, 2022 11:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save allencamal/cfe62dda9fc8132ba6707d5771cac7f1 to your computer and use it in GitHub Desktop.
Save allencamal/cfe62dda9fc8132ba6707d5771cac7f1 to your computer and use it in GitHub Desktop.
Basic actix tls server
// dependencies
// actix-web = {version = "^4.0", features = ["rustls"]}
// env_logger = "0.9.0"
// log = "*"
// rcgen = "^0.9"
// rustls = "*"
// rustls-pemfile = "^0.3.0"
#[actix_web::main]
async fn main() {
env_logger::init();
start_server().await.unwrap();
}
fn start_server() -> actix_web::dev::Server {
actix_web::HttpServer::new(move || actix_web::App::new().service(working).service(failing))
.bind_rustls("127.0.0.1:8085", get_tls_server())
.unwrap()
.run()
}
static DATA: [u8; 20_000_000] = [1u8; 20_000_000]; // 20 MB file
#[actix_web::get("/working")]
async fn working(req: actix_web::HttpRequest) -> actix_web::Result<actix_web::HttpResponse> {
log::info!("{:?}", req.version());
std::thread::sleep(std::time::Duration::from_secs(15));
Ok(actix_web::HttpResponse::Ok().body(DATA.to_vec()))
}
#[actix_web::get("/failing")]
async fn failing(req: actix_web::HttpRequest) -> actix_web::Result<actix_web::HttpResponse> {
log::info!("{:?}", req.version());
actix_web::rt::task::spawn_blocking(|| println!("Request will fail")).await;
std::thread::sleep(std::time::Duration::from_secs(15));
Ok(actix_web::HttpResponse::Ok().body(DATA.to_vec()))
}
fn get_tls_server() -> rustls::ServerConfig {
let server_cert = rcgen::generate_simple_self_signed(vec!["localhost".to_string()]).unwrap();
let server_key = rustls::PrivateKey(
rustls_pemfile::pkcs8_private_keys(&mut server_cert.serialize_private_key_pem().as_bytes())
.unwrap()
.pop()
.unwrap(),
);
let server_certs: Vec<_> =
rustls_pemfile::certs(&mut server_cert.serialize_pem().unwrap().as_bytes())
.unwrap()
.into_iter()
.map(rustls::Certificate)
.collect();
rustls::ServerConfig::builder()
.with_safe_defaults()
.with_no_client_auth()
.with_single_cert(server_certs, server_key)
.unwrap()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment