From 9c90e79575afb3ab2574f1d7e0fc79d7fae90458 Mon Sep 17 00:00:00 2001 From: Ilion Beyst Date: Sun, 20 Feb 2022 23:06:05 +0100 Subject: implement basic configuration --- planetwars-server/Cargo.toml | 1 + planetwars-server/configuration.toml | 1 + planetwars-server/src/lib.rs | 20 ++++++++++++++++---- 3 files changed, 18 insertions(+), 4 deletions(-) create mode 100644 planetwars-server/configuration.toml diff --git a/planetwars-server/Cargo.toml b/planetwars-server/Cargo.toml index 77e8fe9..be34a5f 100644 --- a/planetwars-server/Cargo.toml +++ b/planetwars-server/Cargo.toml @@ -24,6 +24,7 @@ base64 = "0.13.0" zip = "0.5" toml = "0.5" planetwars-matchrunner = { path = "../planetwars-matchrunner" } +config = { version = "0.12", features = ["toml"] } # TODO: remove me shlex = "1.1" diff --git a/planetwars-server/configuration.toml b/planetwars-server/configuration.toml new file mode 100644 index 0000000..ee7002e --- /dev/null +++ b/planetwars-server/configuration.toml @@ -0,0 +1 @@ +database_url = "postgresql://planetwars:planetwars@localhost/planetwars" diff --git a/planetwars-server/src/lib.rs b/planetwars-server/src/lib.rs index 94f2965..60b68ed 100644 --- a/planetwars-server/src/lib.rs +++ b/planetwars-server/src/lib.rs @@ -14,6 +14,7 @@ use axum; use bb8::PooledConnection; use bb8_diesel::{self, DieselConnectionManager}; use diesel::PgConnection; +use serde::Deserialize; use axum::{ async_trait, @@ -30,9 +31,8 @@ const MAPS_DIR: &str = "./data/maps"; type ConnectionPool = bb8::Pool>; -pub async fn api() -> Router { - let database_url = "postgresql://planetwars:planetwars@localhost/planetwars"; - let manager = DieselConnectionManager::::new(database_url); +pub async fn api(configuration: Configuration) -> Router { + let manager = DieselConnectionManager::::new(configuration.database_url); let pool = bb8::Pool::builder().build(manager).await.unwrap(); let api = Router::new() @@ -64,10 +64,22 @@ pub async fn api() -> Router { } pub async fn app() -> Router { - let api = api().await; + let configuration = config::Config::builder() + .add_source(config::File::with_name("configuration.toml")) + .add_source(config::Environment::with_prefix("PLANETWARS")) + .build() + .unwrap() + .try_deserialize() + .unwrap(); + let api = api(configuration).await; Router::new().nest("/api", api) } +#[derive(Deserialize)] +pub struct Configuration { + pub database_url: String, +} + // we can also write a custom extractor that grabs a connection from the pool // which setup is appropriate depends on your application pub struct DatabaseConnection(PooledConnection<'static, DieselConnectionManager>); -- cgit v1.2.3