Skip to content

Commit

Permalink
add ssl toggle config
Browse files Browse the repository at this point in the history
  • Loading branch information
nramos0 committed Oct 22, 2022
1 parent 9e65015 commit ba753d1
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 23 deletions.
8 changes: 5 additions & 3 deletions backend/src/app_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ pub struct ServerConfig {
pub host: String,
pub port: i32,
pub port_ssl: i32,
pub enable_ssl: bool,
pub secret: String,
pub token_time: i64,
pub salt: String,
Expand All @@ -26,8 +27,9 @@ pub struct AppConfig {

impl AppConfig {
pub fn from_env() -> Result<Self, ConfigError> {
let mut cfg = config::Config::new();
cfg.merge(config::Environment::new())?;
cfg.try_into()
config::Config::builder()
.add_source(config::File::new(".env", config::FileFormat::Ini))
.build()
.and_then(|config| config.try_deserialize())
}
}
42 changes: 22 additions & 20 deletions backend/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,10 @@ async fn main() -> std::io::Result<()> {
}

let config = AppConfig::from_env();
let config = {
if config.is_ok() {
config.unwrap()
} else {
eprintln!("Error parsing config: {}", config.unwrap_err());
process::exit(0);
}
};
let config = config.unwrap_or_else(|err| {
eprintln!("Error parsing config: {}", err);
process::exit(0);
});

println!(
"Starting server at http://{0}:{1}/",
Expand All @@ -55,13 +51,7 @@ async fn main() -> std::io::Result<()> {
env_logger::Builder::from_env(Env::default().default_filter_or("info")).init();
let json_config = web::JsonConfig::default().limit(config.server.json_max_size);

let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
builder
.set_private_key_file("key.pem", SslFiletype::PEM)
.unwrap();
builder.set_certificate_chain_file("cert.pem").unwrap();

HttpServer::new(move || {
let server = HttpServer::new(move || {
let cors = Cors::default()
.send_wildcard()
.allow_any_origin()
Expand All @@ -74,7 +64,9 @@ async fn main() -> std::io::Result<()> {
]);

App::new()
.wrap(NormalizePath::default())
.wrap(NormalizePath::new(
actix_web::middleware::normalize::TrailingSlash::Always,
))
.wrap(Logger::default())
.wrap(cors)
.app_data(json_config.clone())
Expand Down Expand Up @@ -109,8 +101,18 @@ async fn main() -> std::io::Result<()> {
.service(user::data::delete_mark)
.service(status)
})
.bind(address)?
.bind_openssl(&ssl_address[..], builder)?
.run()
.await
.bind(address)?;

let server = if config.server.enable_ssl {
let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
builder
.set_private_key_file("key.pem", SslFiletype::PEM)
.unwrap();
builder.set_certificate_chain_file("cert.pem").unwrap();
server.bind_openssl(&ssl_address[..], builder)?
} else {
server
};

server.run().await
}

0 comments on commit ba753d1

Please sign in to comment.