Compare commits

..

3 Commits

4 changed files with 38 additions and 12 deletions

View File

@@ -10,3 +10,4 @@ serde_json = "1.0.145"
toml = "0.9.7"
sqlx = {version = "0.8.6", features = ["postgres"]}
futures-util = "0.3.31"
clap = { version = "4.5.50", features = ["derive"] }

View File

@@ -1,5 +1,5 @@
[application]
[server]
# Change with actual location of assets
assets=""
assets="./assets"
# Set bind address
bind="127.0.0.1:8080"

View File

@@ -3,9 +3,11 @@ mod middleware;
mod pages;
use actix_web::{App, HttpServer, web};
use clap::Parser;
use serde::Deserialize;
use std::fs::File;
use std::io::Read;
use std::process::exit;
use toml::from_slice;
use middleware::MimeType;
@@ -15,6 +17,13 @@ use pages::{
projects::{project, projects},
};
#[derive(Parser)]
#[command(name = "aindustries-be", version, about = "This is the amazing webserver for aindustries.be!", long_about = None)]
struct Cli {
#[arg(short, long, value_name = "CONFIG", help = "Path to config file, defaults to /etc/aindustries-be/config.toml")]
config: Option<String>,
}
#[derive(Deserialize)]
struct Config {
server: ServerConfig,
@@ -32,13 +41,29 @@ struct AppState {
#[actix_web::main]
async fn main() {
let mut config_file =
File::open("/etc/aindustries-be/config.toml").expect("Could not open config file");
let cli = Cli::parse();
let config_file_path = cli
.config
.unwrap_or("/etc/aindustries-be/config.toml".to_string());
let mut config_file = match File::open(&config_file_path) {
Ok(config_file) => config_file,
Err(e) => {
eprintln!("Could not open config file ({config_file_path}): {e}");
exit(1);
}
};
let mut buf = vec![];
config_file
.read_to_end(&mut buf)
.expect("Could not read config file");
let config: Config = from_slice(&buf).expect("Could not parse config");
if let Err(e) = config_file.read_to_end(&mut buf) {
eprintln!("Could not read config file: {e}");
exit(1);
}
let config: Config = match from_slice(&buf) {
Ok(config) => config,
Err(e) => {
eprintln!("Could not parse config file {e}");
exit(1);
}
};
let bind_address = config.server.bind;
let assets = config.server.assets;
let data = web::Data::new(AppState { assets });
@@ -56,7 +81,7 @@ async fn main() {
match server.run().await {
Ok(_) => {}
Err(e) => {
eprintln!("An error occurred: {}", e);
eprintln!("An error occurred: {e}");
}
}
}

View File

@@ -8,8 +8,8 @@ use std::path::PathBuf;
#[get("/static/{file_type}/{file_name}")]
async fn file(file: Path<(String, String)>, data: web::Data<AppState>) -> impl Responder {
let mut path = PathBuf::from(&data.assets);
path.push(&file.0.replace("/", ""));
path.push(&file.1.replace("/", ""));
path.push(file.0.replace("/", ""));
path.push(file.1.replace("/", ""));
let mut file = File::open(path).unwrap();
let mut bytes = Vec::new();
if file.read_to_end(&mut bytes).is_err() {