From 08bac19160dcbc798bf075acf0667da941e76e97 Mon Sep 17 00:00:00 2001 From: Evie Viau Date: Sat, 4 Feb 2023 02:42:11 -0800 Subject: [PATCH] Connect to database on start --- Cargo.lock | 2 ++ Cargo.toml | 2 ++ src/main.rs | 59 +++++++++++++++++++++++++++++++++++++++++++++-------- 3 files changed, 55 insertions(+), 8 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 0913fcf..192ee9c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1448,6 +1448,8 @@ dependencies = [ "askama", "askama_axum", "axum", + "dotenvy", + "log", "migration", "sea-orm 0.11.0-rc.1", "tokio", diff --git a/Cargo.toml b/Cargo.toml index fc91690..9d5b6e9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,3 +19,5 @@ migration = { path = "./migration" } axum = "0.6.4" askama = { version = "0.11.1", features = ["with-axum"] } askama_axum = "0.2.1" +dotenvy = "0.15.6" +log = "0.4.17" diff --git a/src/main.rs b/src/main.rs index 8fcdbf2..e0a1be9 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,21 +1,64 @@ -use std::net::SocketAddr; +use std::{net::SocketAddr, env}; +use std::str::FromStr; use axum::{Router, routing::get}; +use log::{info, error}; +use sea_orm::{Database, DatabaseConnection}; mod routes; mod entities; #[tokio::main] async fn main() { + env::set_var("RUST_LOG", "info"); tracing_subscriber::fmt::init(); - let app = Router::new() - .route("/", get(routes::root::root)); + dotenvy::dotenv().ok(); - let listen_addr = SocketAddr::from(([0, 0, 0, 0], 3621)); + info!("Starting up.."); - axum::Server::bind(&listen_addr) - .serve(app.into_make_service()) + let db_url = env::var("DATABASE_URL").expect("DATABASE_URL is not set in the enviroment! HALTING"); + let host = env::var("HOST").unwrap_or("0.0.0.0".to_string()); + let port = env::var("PORT").unwrap_or("3621".to_string()); + + let server_url = format!("{host}:{port}"); + + info!("Connecting to the database..."); + + let db_conn = Database::connect(db_url) .await - .unwrap(); -} \ No newline at end of file + .expect("Failed to connect to the database! HALTING"); + //Migrator::up(&db_conn, None).await.expect("Failed to run migrations! HALTING"); + + info!("Connected to database!"); + + let app_state = AppState { db_conn }; + + let app = Router::new() + .route("/", get(routes::root::root)) + .with_state(app_state); + + info!("Attempting to bind to address..."); + + let listen_addr = SocketAddr::from_str(&server_url).expect("Failed to parse host and port! HALTING"); + + let bind = axum::Server::try_bind(&listen_addr); + + match bind { + Ok(bind) => { + info!("Binded to address successfully!"); + info!("Started!"); + bind.serve(app.into_make_service()) + .await + .unwrap(); + }, + Err(_) => { + panic!("Failed to bind! HALTING") + }, + } +} + +#[derive(Clone)] +struct AppState { + db_conn: DatabaseConnection, +}