moved config settings to separate module.

This commit is contained in:
2022-06-18 21:24:11 -04:00
parent e79cf82b62
commit 217aea7a97
7 changed files with 240 additions and 34 deletions

View File

@ -1,26 +1,26 @@
use config::Config;
use tide::{http::StatusCode, Request, Response};
mod settings;
use settings::Settings;
#[async_std::main]
async fn main() -> tide::Result<()> {
let settings = Config::builder()
.set_default("address", "127.0.0.1")?
.set_default("port", "9090")?
.add_source(
config::Environment::with_prefix("MTT")
.try_parsing(true)
.separator("_")
.list_separator(" "),
)
.build()
.unwrap();
//let settings = Config::builder()
// .set_default("address", "127.0.0.1")?
// .set_default("port", 9090)?
// .add_source(
// config::Environment::with_prefix("MTT")
// .try_parsing(true)
// .separator("_")
// .list_separator(" "),
// )
// .build()
// .unwrap();
let sett = Settings::new().unwrap();
let app = app_setup().await;
app.listen(format!(
"{}:{}",
settings.get_string("address").unwrap(),
settings.get_string("port").unwrap()
))
.await?;
app.listen(format!("{}:{}", sett.address, sett.port))
.await?;
Ok(())
}
@ -45,7 +45,7 @@ async fn home(_req: Request<()>) -> tide::Result {
}
#[cfg(test)]
mod basic_tests {
mod server_app {
use super::*;
use tide_testing::TideTestingExt;

50
src/settings.rs Normal file
View File

@ -0,0 +1,50 @@
use config::{Config, ConfigError};
use serde::Deserialize;
#[derive(Debug, Deserialize)]
//#[allow(unused)]
pub struct Settings {
pub address: String,
pub port: u16,
}
impl Settings {
pub fn new() -> Result<Self, ConfigError> {
let s = Config::builder()
.set_default("port", 9090)?
.set_default("address", "127.0.0.1")?
.add_source(
config::Environment::with_prefix("MTT")
.try_parsing(true)
.separator("_")
.list_separator(" "),
)
.build()?;
s.try_deserialize()
}
}
#[cfg(test)]
mod settings_tests {
use super::*;
use serial_test::serial;
#[test]
#[serial]
fn defaults() {
let set = Settings::new().unwrap();
println!("{:?}", set);
assert_eq!(set.port, 9090);
assert_eq!(set.address, "127.0.0.1");
}
#[test]
#[serial]
fn port_env() {
std::env::set_var("MTT_PORT", "7825");
let set = Settings::new().unwrap();
println!("{:?}", set);
assert_eq!(set.port, 7825);
std::env::remove_var("MTT_PORT");
}
}