use actix_web::middleware::Logger; use actix_web::{web, App, HttpServer}; use openssl::ssl::{SslAcceptor, SslMethod}; use crate::app_config::AppConfig; use crate::crypto::pki; pub mod custom_error; pub mod energy_controller; pub mod pki_controller; pub mod server_controller; /// Start unsecure (HTTP) server pub async fn unsecure_server() -> anyhow::Result<()> { log::info!( "Unsecure server starting to listen on {} for {}", AppConfig::get().unsecure_listen_address, AppConfig::get().unsecure_origin() ); HttpServer::new(|| { App::new() .wrap(Logger::default()) .route("/", web::get().to(server_controller::unsecure_home)) .route("/pki/{file}", web::get().to(pki_controller::serve_pki_file)) }) .bind(&AppConfig::get().unsecure_listen_address)? .run() .await?; Ok(()) } /// Start secure (HTTPS) server pub async fn secure_server() -> anyhow::Result<()> { let web_ca = pki::CertData::load_web_ca()?; let server_cert = pki::CertData::load_server()?; let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap(); builder.set_private_key(&server_cert.key)?; builder.set_certificate(&server_cert.cert)?; builder.add_extra_chain_cert(web_ca.cert)?; log::info!( "Secure server starting to listen on {} for {}", AppConfig::get().listen_address, AppConfig::get().secure_origin() ); HttpServer::new(|| { App::new() .wrap(Logger::default()) .route("/", web::get().to(server_controller::secure_home)) .route( "/api/energy/curr_consumption", web::get().to(energy_controller::curr_consumption), ) }) .bind_openssl(&AppConfig::get().listen_address, builder)? .run() .await?; Ok(()) }