Skip to content

Commit

Permalink
use config struct to load the env variable into struct
Browse files Browse the repository at this point in the history
  • Loading branch information
m4salah committed Dec 30, 2023
1 parent 3df9e8f commit 086e98c
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 9 deletions.
3 changes: 2 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
DATABASE_URL=postgres://shuttle_test:password@localhost:5432/shuttle
GEOCODING_API_KEY=
GEOCODING_API_KEY=
PORT=8000
11 changes: 11 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
@@ -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,
}
38 changes: 30 additions & 8 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -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<Postgres>) -> Router {
handlers::router(pool)

fn app(pool: Pool<Postgres>, 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<dyn Error>> {
// 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(())
}

0 comments on commit 086e98c

Please sign in to comment.