unleash_api_client/
config.rs

1// Copyright 2020 Cognite AS
2
3//! Convenient configuration glue.
4//!
5//! This module grabs configuration settings from the environment in an
6//! easy-to-hand-off fashion. It is loosely coupled so that apps using
7//! different configuration mechanisms are not required to use it or even
8//! implement a trait.
9
10use std::env;
11
12#[derive(Debug, Default)]
13pub struct EnvironmentConfig {
14    pub api_url: String,
15    pub app_name: String,
16    pub instance_id: String,
17    pub secret: Option<String>,
18}
19
20impl EnvironmentConfig {
21    /// Retrieve a configuration from environment variables.alloc
22    ///
23    /// UNLEASH_API_URL: <http://host.example.com:1234/api>
24    /// UNLEASH_APP_NAME: example-app
25    /// UNLEASH_INSTANCE_ID: instance-512
26    /// UNLEASH_CLIENT_SECRET: unset | some-secret-value
27    pub fn from_env() -> Result<Self, Box<dyn std::error::Error + Send + Sync + 'static>> {
28        let mut result = EnvironmentConfig::default();
29        let api_url = env::var("UNLEASH_API_URL");
30        if let Ok(api_url) = api_url {
31            result.api_url = api_url;
32        } else {
33            return Err(anyhow::anyhow!("UNLEASH_API_URL not set").into());
34        };
35        if let Ok(app_name) = env::var("UNLEASH_APP_NAME") {
36            result.app_name = app_name;
37        } else {
38            return Err(anyhow::anyhow!("UNLEASH_APP_NAME not set").into());
39        };
40        if let Ok(instance_id) = env::var("UNLEASH_INSTANCE_ID") {
41            result.instance_id = instance_id;
42        } else {
43            return Err(anyhow::anyhow!("UNLEASH_INSTANCE_ID not set").into());
44        };
45        result.secret = env::var("UNLEASH_CLIENT_SECRET").ok();
46        Ok(result)
47    }
48}