From 086e98c6a496875c20d51ac5c98497f34e25ada2 Mon Sep 17 00:00:00 2001 From: "Mohamed A. Salah" Date: Sat, 30 Dec 2023 17:35:30 +0200 Subject: [PATCH] use config struct to load the env variable into struct --- .env.example | 3 ++- src/config.rs | 11 +++++++++++ src/main.rs | 38 ++++++++++++++++++++++++++++++-------- 3 files changed, 43 insertions(+), 9 deletions(-) create mode 100644 src/config.rs diff --git a/.env.example b/.env.example index 53f32d5..7b79301 100644 --- a/.env.example +++ b/.env.example @@ -1,2 +1,3 @@ DATABASE_URL=postgres://shuttle_test:password@localhost:5432/shuttle -GEOCODING_API_KEY= \ No newline at end of file +GEOCODING_API_KEY= +PORT=8000 \ No newline at end of file diff --git a/src/config.rs b/src/config.rs new file mode 100644 index 0000000..f1f3d96 --- /dev/null +++ b/src/config.rs @@ -0,0 +1,11 @@ +#[derive(clap::Parser, Clone, Debug)] +pub struct Config { + #[clap(long, env)] + pub database_url: String, + + #[clap(long, env)] + pub geocoding_api_key: String, + + #[clap(long, env, default_value = "8000")] + pub port: u16, +} diff --git a/src/main.rs b/src/main.rs index 28d9eaf..2a4c54f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,17 +1,39 @@ -use std::env; +use std::{error::Error, net::SocketAddr}; use axum::Router; +use clap::Parser; use sqlx::{PgPool, Pool, Postgres}; +mod config; mod handlers; -fn app(pool: Pool) -> Router { - handlers::router(pool) + +fn app(pool: Pool, geocoding_api_key: String) -> Router { + handlers::router(pool, geocoding_api_key) } -#[shuttle_runtime::main] -async fn shuttle_service() -> shuttle_axum::ShuttleAxum { +#[tokio::main] +async fn main() -> Result<(), Box> { + // load environment variable from .env file dotenv::dotenv().ok(); - let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set the env variable"); - let pool = PgPool::connect(&database_url).await.unwrap(); - Ok(app(pool).into()) + + // initialize the tracing + tracing_subscriber::fmt().init(); + + // load the env variable into config struct + let config = config::Config::parse(); + tracing::info!("config .env {:?}", config); + + // initialize the database pool + let pool = PgPool::connect(&config.database_url).await.unwrap(); + + // bind an address from the env port + let addr = SocketAddr::from(([0, 0, 0, 0], config.port)); + tracing::info!("listening on {}", addr); + + // start the server + axum::Server::bind(&addr) + .serve(app(pool, config.geocoding_api_key).into_make_service()) + .await + .unwrap(); + Ok(()) }