feat: add configurability

This commit is contained in:
Sandro Eiler 2024-01-01 14:34:42 +01:00
parent 89ea0995bb
commit 8257255dc2
10 changed files with 1406 additions and 26 deletions

View file

@ -0,0 +1,37 @@
#[derive(serde::Deserialize)]
pub struct Settings {
pub database: DatabaseSettings,
pub application_port: u16,
}
#[derive(serde::Deserialize)]
pub struct DatabaseSettings {
pub username: String,
pub password: String,
pub port: u16,
pub host: String,
pub database_name: String,
}
pub fn get_configuration() -> Result<Settings, config::ConfigError> {
// Initialise our configuration reader
let settings = config::Config::builder()
// Add configuration values from a file named `configuration.yaml`.
.add_source(config::File::new(
"configuration.yaml",
config::FileFormat::Yaml,
))
.build()?;
// Try to convert the configuration values it read into
// our Settings type
settings.try_deserialize::<Settings>()
}
impl DatabaseSettings {
pub fn connection_string(&self) -> String {
format!(
"postgres://{}:{}@{}:{}/{}",
self.username, self.password, self.host, self.port, self.database_name
)
}
}

View file

@ -1,9 +1,11 @@
use tokio::net::TcpListener;
use learn_axum::startup;
use learn_axum::configuration::get_configuration;
use tokio::net::TcpListener;
#[tokio::main]
async fn main() {
let addr = format!("127.0.0.1:{}", "3000");
let configuration = get_configuration().expect("Failed to read configuration.");
let addr = format!("127.0.0.1:{}", configuration.application_port);
let listener = TcpListener::bind(addr).await.unwrap(); //.expect("Unable to bind to port");
startup::run(listener).await.unwrap();
}