torrust_index_backend/bootstrap/
config.rs

1//! Initialize configuration from file or env var.
2//!
3//! All environment variables are prefixed with `TORRUST_IDX_BACK_`.
4use std::env;
5
6// Environment variables
7
8/// The whole `config.toml` file content. It has priority over the config file.
9/// Even if the file is not on the default path.
10pub const ENV_VAR_CONFIG: &str = "TORRUST_IDX_BACK_CONFIG";
11
12/// The `config.toml` file location.
13pub const ENV_VAR_CONFIG_PATH: &str = "TORRUST_IDX_BACK_CONFIG_PATH";
14
15/// If present, CORS will be permissive.
16pub const ENV_VAR_CORS_PERMISSIVE: &str = "TORRUST_IDX_BACK_CORS_PERMISSIVE";
17
18// Default values
19
20pub const ENV_VAR_DEFAULT_CONFIG_PATH: &str = "./config.toml";
21
22use crate::config::Configuration;
23
24/// Initialize configuration from file or env var.
25///
26/// # Panics
27///
28/// Will panic if configuration is not found or cannot be parsed
29pub async fn init_configuration() -> Configuration {
30    if env::var(ENV_VAR_CONFIG).is_ok() {
31        println!("Loading configuration from env var `{ENV_VAR_CONFIG}`");
32
33        Configuration::load_from_env_var(ENV_VAR_CONFIG).unwrap()
34    } else {
35        let config_path = env::var(ENV_VAR_CONFIG_PATH).unwrap_or_else(|_| ENV_VAR_DEFAULT_CONFIG_PATH.to_string());
36
37        println!("Loading configuration from config file `{config_path}`");
38
39        match Configuration::load_from_file(&config_path).await {
40            Ok(config) => config,
41            Err(error) => {
42                panic!("{}", error)
43            }
44        }
45    }
46}