Added database to AppState

This commit is contained in:
2025-10-27 08:45:35 +01:00
parent 9c79881c4b
commit 0fe13b6ce7
2 changed files with 34 additions and 2 deletions

View File

@@ -2,4 +2,10 @@
# Change with actual location of assets # Change with actual location of assets
assets="./assets" assets="./assets"
# Set bind address # Set bind address
bind="127.0.0.1:8080" bind="127.0.0.1:8080"
[database]
address="127.0.0.1:5432"
user="web"
password="apassword"
database_name="website"

View File

@@ -5,6 +5,7 @@ mod pages;
use actix_web::{App, HttpServer, web}; use actix_web::{App, HttpServer, web};
use clap::Parser; use clap::Parser;
use serde::Deserialize; use serde::Deserialize;
use sqlx::PgPool;
use std::fs::File; use std::fs::File;
use std::io::Read; use std::io::Read;
use std::process::exit; use std::process::exit;
@@ -32,6 +33,7 @@ struct Cli {
#[derive(Deserialize)] #[derive(Deserialize)]
struct Config { struct Config {
server: ServerConfig, server: ServerConfig,
database: DatabaseConfig,
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@@ -40,8 +42,17 @@ struct ServerConfig {
bind: String, bind: String,
} }
#[derive(Deserialize)]
struct DatabaseConfig {
address: String,
user: String,
password: String,
database_name: String,
}
struct AppState { struct AppState {
assets: String, assets: String,
pool: PgPool,
} }
#[actix_web::main] #[actix_web::main]
@@ -71,7 +82,22 @@ async fn main() {
}; };
let bind_address = config.server.bind; let bind_address = config.server.bind;
let assets = config.server.assets; 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 || { if let Ok(server) = HttpServer::new(move || {
App::new().app_data(data.clone()).service(file).service( App::new().app_data(data.clone()).service(file).service(
web::scope("") web::scope("")