From adc6744d16f03f16e57755081af68453bf7049d2 Mon Sep 17 00:00:00 2001 From: Alexey Velikiy Date: Tue, 2 Nov 2021 16:08:01 +0300 Subject: [PATCH] env vs config #12 --- Makefile | 1 + server/.gitignore | 1 + server/config.example.toml | 3 +++ server/src/config.rs | 27 ++++++++++++++++++++++++--- 4 files changed, 29 insertions(+), 3 deletions(-) create mode 100644 server/config.example.toml diff --git a/Makefile b/Makefile index 49b6ed2..21da58d 100644 --- a/Makefile +++ b/Makefile @@ -3,6 +3,7 @@ all: server client cp server/target/x86_64-unknown-linux-musl/release/hastic release mkdir release/public cp -r client/dist/* release/public/ + cp server/config.example.toml release/config.toml server: diff --git a/server/.gitignore b/server/.gitignore index 991eda0..c222e2c 100644 --- a/server/.gitignore +++ b/server/.gitignore @@ -1,3 +1,4 @@ target/* data.db data/* +config.toml diff --git a/server/config.example.toml b/server/config.example.toml new file mode 100644 index 0000000..3f19cbd --- /dev/null +++ b/server/config.example.toml @@ -0,0 +1,3 @@ +port = 8000 +query = "rate(go_memstats_alloc_bytes_total[5m])" +prom_url = "http://localhost:9090" \ No newline at end of file diff --git a/server/src/config.rs b/server/src/config.rs index ac1ccb3..836affa 100644 --- a/server/src/config.rs +++ b/server/src/config.rs @@ -1,3 +1,6 @@ +use std::collections::HashMap; + + pub struct Config { pub prom_url: String, pub query: String, @@ -7,10 +10,28 @@ pub struct Config { // TODO: use actual config and env variables impl Config { pub fn new() -> Config { + + let mut config = config::Config::default(); + + if std::path::Path::new("config.toml").exists() { + config.merge(config::File::with_name("config")).unwrap(); + } + config.merge(config::Environment::with_prefix("HASTIC")).unwrap(); + + if config.get::("port").is_err() { + config.set("port", "8000").unwrap(); + } + if config.get::("prom_url").is_err() { + config.set("prom_url", "http://localhost:9090").unwrap(); + } + if config.get::("query").is_err() { + config.set("query", "rate(go_memstats_alloc_bytes_total[5m])").unwrap(); + } + Config { - port: 8000, - prom_url: "http://localhost:9090".to_owned(), - query: "rate(go_memstats_alloc_bytes_total[5m])".to_owned(), + port: config.get::("port").unwrap(), + prom_url: config.get("prom_url").unwrap(), + query: config.get("query").unwrap() } } }