Browse Source

Update the environment variable stuff

Lee Morgan 2 tháng trước cách đây
mục cha
commit
e56251667b
1 tập tin đã thay đổi với 14 bổ sung6 xóa
  1. 14 6
      src/main.rs

+ 14 - 6
src/main.rs

@@ -17,10 +17,9 @@ async fn main() -> Result<(), AppError> {
     //Environment variables
     dotenvy::dotenv().expect("Failed to load .env file");
 
-    let port:u16 = env::var("PORT")
-        .expect("Environment variable PORT not set")
-        .parse()
-        .expect("PORT must be a valid number");
+    let database_url: String = env_var("DATABASE_URL");
+    let port: u16 = env_var("PORT");
+    let app_env: String= env_var("APP_ENV");
 
     //MQTT
     let mut options = MqttOptions::new("actix_server", "localhost", 1883);
@@ -41,8 +40,7 @@ async fn main() -> Result<(), AppError> {
     let mqtt_client = client;
 
     //Postgres
-    let app_env = std::env::var("APP_ENV").unwrap_or_else(|_| "development".to_string());
-    let pool = PgPool::connect("postgres://leemorgan:password123@localhost:5432/homo")
+    let pool = PgPool::connect(&database_url)
         .await
         .expect("Failed to start Postgres");
 
@@ -81,3 +79,13 @@ async fn main() -> Result<(), AppError> {
 
     Ok(())
 }
+
+fn env_var<T: std::str::FromStr>(key: &str) -> T
+where
+    T::Err: std::fmt::Debug,
+{
+    env::var(key)
+        .unwrap_or_else(|_| panic!("Environment variable {} not set", key))
+        .parse()
+        .unwrap_or_else(|_| panic!("{} could not be parsed", key))
+}