Connect to database on start
This commit is contained in:
parent
b4cac9d1dc
commit
08bac19160
3 changed files with 55 additions and 8 deletions
2
Cargo.lock
generated
2
Cargo.lock
generated
|
@ -1448,6 +1448,8 @@ dependencies = [
|
|||
"askama",
|
||||
"askama_axum",
|
||||
"axum",
|
||||
"dotenvy",
|
||||
"log",
|
||||
"migration",
|
||||
"sea-orm 0.11.0-rc.1",
|
||||
"tokio",
|
||||
|
|
|
@ -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"
|
||||
|
|
59
src/main.rs
59
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();
|
||||
}
|
||||
.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,
|
||||
}
|
||||
|
|
Reference in a new issue