read configuration from multiple locations

This commit is contained in:
realaravinth 2021-05-12 18:02:16 +05:30
parent a4b409e914
commit 4df220edad
No known key found for this signature in database
GPG key ID: AD9F0F08E855ED88
2 changed files with 23 additions and 5 deletions

View file

@ -96,8 +96,10 @@ $ cd guard && cargo build
Guard is highly configurable.
Configuration is applied/merged in the following order:
1. `config/default.toml`
2. environment variables.
1. path to configuration file passed in via `GUARD_CONFIG`
2. `./config/default.toml`
3. `/etc/guard/config.toml`
4. environment variables.
### Setup
@ -125,3 +127,4 @@ you will be overriding the values set in the configuration files.
| `GUARD_SERVER_PORT` (or) `PORT`\*\* | The port on which you want wagon to listen to |
| `GUARD_SERVER_IP` | The IP address on which you want wagon to listen to |
| `GUARD_SERVER_STATIC_FILES_DIR` | Path to directory containing static files |
| `GUARD_CONFIG` | Path to config file |

View file

@ -15,6 +15,7 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
use std::env;
use std::path::Path;
use config::{Config, ConfigError, Environment, File};
use log::debug;
@ -97,8 +98,19 @@ impl Settings {
s.set_default("database.pool", 2.to_string())
.expect("Couldn't get the number of CPUs");
// merging default config from file
s.merge(File::with_name("./config/default.toml"))?;
const CURRENT_DIR: &str = "./config/default.toml";
const ETC: &str = "/etc/guard/config.toml";
if let Ok(path) = env::var("GUARD_CONFIG") {
s.merge(File::with_name(&path))?;
} else if Path::new(CURRENT_DIR).exists() {
// merging default config from file
s.merge(File::with_name(CURRENT_DIR))?;
} else if Path::new(ETC).exists() {
s.merge(File::with_name(ETC))?;
} else {
log::warn!("configuration file not found");
}
s.merge(Environment::with_prefix("GUARD"))?;
@ -122,7 +134,10 @@ impl Settings {
set_database_url(&mut s);
s.try_into()
match s.try_into() {
Ok(val) => Ok(val),
Err(e) => Err(ConfigError::Message(format!("\n\nError: {}. If it says missing fields, then please refer to https://github.com/mCaptcha/guard#configuration to learn more about how guard reads configuration\n\n", e)))?,
}
}
}