Automatically create a default file config if it doesn't exist.
[rup.git] / src / main.rs
index f385a0e..af1bd95 100644 (file)
@@ -1,16 +1,16 @@
-extern crate actix_web;
+
 extern crate listenfd;
 extern crate askama;
 extern crate percent_encoding;
 
 use listenfd::ListenFd;
 use actix_files as fs;
-use actix_web::{web, middleware, App, HttpServer, HttpResponse, web::Query};
+use actix_web::{ web, middleware, App, HttpServer, HttpResponse, web::Query };
 use askama::Template;
 
-use std::{fs::File, path::Path, env::args, io::prelude::*};
-use ron::de::from_reader;
-use serde::Deserialize;
+use std::{ fs::File, path::Path, env::args, io::prelude::* };
+use ron::{ de::from_reader, ser::{ to_string_pretty, PrettyConfig } };
+use serde::{ Deserialize, Serialize };
 
 use itertools::Itertools;
 
@@ -45,17 +45,31 @@ fn main_page(query: Query<Request>, key: &str) -> HttpResponse {
     HttpResponse::Ok().content_type("text/html").body(s)
 }
 
-#[derive(Debug, Deserialize)]
+#[derive(Debug, Deserialize, Serialize)]
 struct Config {
     port: u16
 }
 
+const DEFAULT_CONFIG: Config = Config { port: 8082 };
+
 fn get_exe_name() -> String {
     let first_arg = std::env::args().next().unwrap();
     let sep: &[_] = &['\\', '/'];
     first_arg[first_arg.rfind(sep).unwrap()+1..].to_string()
 }
 
+fn load_config() -> Config {
+    // unwrap_or_else(|_| panic!("Failed to open configuration file {}", consts::FILE_CONF));
+    match File::open(consts::FILE_CONF) {
+        Ok(file) => from_reader(file).unwrap_or_else(|_| panic!("Failed to open configuration file {}", consts::FILE_CONF)),
+        Err(_) => {
+            let mut file = File::create(consts::FILE_CONF) .unwrap();
+            file.write_all(to_string_pretty(&DEFAULT_CONFIG, PrettyConfig::new()).unwrap().as_bytes()).unwrap(); // We do not use 'to_writer' because it can't pretty format the output.
+            DEFAULT_CONFIG
+        }
+    }
+}
+
 fn read_key() -> String {
     let mut key = String::new();
     File::open(consts::FILE_KEY)
@@ -77,6 +91,7 @@ fn write_key(key : &str) {
 }
 
 #[actix_rt::main]
+
 async fn main() -> std::io::Result<()> {
     let key = {
         // If the key file doesn't exist then create a new one with a random key in it.
@@ -94,13 +109,7 @@ async fn main() -> std::io::Result<()> {
 
     println!("Starting RUP as web server...");
 
-    let config: Config = {
-        let f = File::open(consts::FILE_CONF).unwrap_or_else(|_| panic!("Failed to open configuration file {}", consts::FILE_CONF));
-        match from_reader(f) {
-            Ok(c) => c,
-            Err(e) => panic!("Failed to load config: {}", e)
-        }
-    };
+    let config = load_config();
 
     println!("Configuration: {:?}", config);