From 0fe13b6ce71521cad48acfc82b1c487c6e10de26 Mon Sep 17 00:00:00 2001 From: AINDUSTRIES Date: Mon, 27 Oct 2025 08:45:35 +0100 Subject: [PATCH] Added database to AppState --- config.toml | 8 +++++++- src/main.rs | 28 +++++++++++++++++++++++++++- 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/config.toml b/config.toml index eb15266..6218919 100644 --- a/config.toml +++ b/config.toml @@ -2,4 +2,10 @@ # Change with actual location of assets assets="./assets" # Set bind address -bind="127.0.0.1:8080" \ No newline at end of file +bind="127.0.0.1:8080" + +[database] +address="127.0.0.1:5432" +user="web" +password="apassword" +database_name="website" \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index 783b333..9dd6f1a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -5,6 +5,7 @@ mod pages; use actix_web::{App, HttpServer, web}; use clap::Parser; use serde::Deserialize; +use sqlx::PgPool; use std::fs::File; use std::io::Read; use std::process::exit; @@ -32,6 +33,7 @@ struct Cli { #[derive(Deserialize)] struct Config { server: ServerConfig, + database: DatabaseConfig, } #[derive(Deserialize)] @@ -40,8 +42,17 @@ struct ServerConfig { bind: String, } +#[derive(Deserialize)] +struct DatabaseConfig { + address: String, + user: String, + password: String, + database_name: String, +} + struct AppState { assets: String, + pool: PgPool, } #[actix_web::main] @@ -71,7 +82,22 @@ async fn main() { }; let bind_address = config.server.bind; let assets = config.server.assets; - let data = web::Data::new(AppState { assets }); + let database_address = format!( + "postgres://{}:{}@{}/{}", + config.database.user, + config.database.password, + config.database.address, + config.database.database_name + ); + let pool = match PgPool::connect(&database_address).await { + Ok(pool) => pool, + Err(e) => { + eprintln!("Could not connect to database: {e}"); + exit(1); + } + }; + let assets = assets.replace("~", "/home/conta/Code/aindustries.be/assets"); + let data = web::Data::new(AppState { assets, pool }); if let Ok(server) = HttpServer::new(move || { App::new().app_data(data.clone()).service(file).service( web::scope("")