From 7d190c426ab6b7702a044d40114098ca95121676 Mon Sep 17 00:00:00 2001 From: rozetko Date: Fri, 24 Dec 2021 20:40:57 +0300 Subject: [PATCH] env variables configuration #55 --- server/src/config.rs | 36 ++++++++++++++++++++++++++++++++---- 1 file changed, 32 insertions(+), 4 deletions(-) diff --git a/server/src/config.rs b/server/src/config.rs index 3ff9744..6bbdcbc 100644 --- a/server/src/config.rs +++ b/server/src/config.rs @@ -1,5 +1,7 @@ use subbeat::types::{DatasourceConfig, InfluxConfig, PrometheusConfig}; +use std::env; + #[derive(Clone)] pub struct WebhookAlertingConfig { pub endpoint: String, @@ -62,7 +64,7 @@ fn resolve_alerting(config: &config::Config) -> anyhow::Result("alerting.type").unwrap(); if analytic_type != "webhook" { return Err(anyhow::format_err!( - "unknown alerting typy {}", + "unknown alerting type: {}", analytic_type )); } @@ -75,6 +77,33 @@ fn resolve_alerting(config: &config::Config) -> anyhow::Result alerting.type +pub fn update_from_env(config: &mut config::Config) { + let overrides = + env::vars().filter_map(|(key, value)| parse_env(&key).map(|index| (index, value))); + + for (key, value) in overrides { + println!("{} => {}", key, value); + config.set(&key, value).unwrap(); + } +} + +fn parse_env(key: &str) -> Option { + const PREFIX: &str = "HASTIC_"; + + if key.starts_with(PREFIX) { + let key = &key[PREFIX.len()..]; + + Some(key.to_lowercase().replace("__", ".").replace("_", "-")) + } else { + None + } +} + impl Config { pub fn new() -> anyhow::Result { let mut config = config::Config::default(); @@ -83,14 +112,13 @@ impl Config { config.merge(config::File::with_name("config")).unwrap(); } - config - .merge(config::Environment::with_prefix("HASTIC")) - .unwrap(); + update_from_env(&mut config); if config.get::("port").is_err() { config.set("port", "8000").unwrap(); } + // TODO: print resulted config (perfectly, it needs adding `derive(Debug)` in `subbeat`'s `DatasourceConfig`) Ok(Config { port: config.get::("port").unwrap(), datasource_config: resolve_datasource(&config)?,