Added database to AppState
This commit is contained in:
@@ -2,4 +2,10 @@
|
||||
# Change with actual location of assets
|
||||
assets="./assets"
|
||||
# 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"
|
||||
28
src/main.rs
28
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("")
|
||||
|
||||
Reference in New Issue
Block a user