From 0918700a854b733635511daef2d0bba208246ca3 Mon Sep 17 00:00:00 2001 From: Joshua Goins Date: Sat, 11 May 2024 13:13:03 -0400 Subject: [PATCH] Fix the admin server not creating config.json if not found --- .gitignore | 1 + src/bin/kawari-admin.rs | 40 +++++++++++++++++++++------------------- src/config.rs | 8 ++++++++ 3 files changed, 30 insertions(+), 19 deletions(-) diff --git a/.gitignore b/.gitignore index c403c34..db41fce 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ /target .idea/ +config.json \ No newline at end of file diff --git a/src/bin/kawari-admin.rs b/src/bin/kawari-admin.rs index 703f9bf..248168d 100644 --- a/src/bin/kawari-admin.rs +++ b/src/bin/kawari-admin.rs @@ -10,6 +10,14 @@ use axum::response::{Html, Redirect}; use axum::routing::post; use kawari::config::Config; +fn get_config() -> Config { + if let Ok(data) = std::fs::read_to_string("config.json") { + serde_json::from_str(&data).expect("Failed to parse") + } else { + Config::default() + } +} + #[derive(Debug, Clone, Serialize, Deserialize)] struct GateStatus { status: i32, @@ -18,14 +26,9 @@ struct GateStatus { async fn root() -> Html { tracing::info!("Requesting gate status..."); - // read config - if let Ok(data) = std::fs::read_to_string("config.json") { - let config: Config = serde_json::from_str(&data).expect("Failed to parse"); + let config = get_config(); - Html(format!("

Gate open:{}

", config.gate_open)) - } else { - Html(format!("unknown error")) - } + Html(format!("

Gate open:{}

", config.gate_open)) } #[derive(Deserialize, Debug)] @@ -37,21 +40,20 @@ struct Input { async fn apply(Form(input): Form) -> Redirect { tracing::info!("Apply config changes..."); - if let Ok(data) = std::fs::read_to_string("config.json") { - let mut config: Config = serde_json::from_str(&data).expect("Failed to parse"); - if let Some(gate_open) = input.gate_open { - config.gate_open = gate_open == "on"; - } else { - config.gate_open = false; - } + let mut config = get_config(); - serde_json::to_writer( - &std::fs::File::create("config.json").unwrap(), - &config, - ) - .expect("TODO: panic message"); + if let Some(gate_open) = input.gate_open { + config.gate_open = gate_open == "on"; + } else { + config.gate_open = false; } + serde_json::to_writer( + &std::fs::File::create("config.json").unwrap(), + &config, + ) + .expect("TODO: panic message"); + Redirect::to("/") } diff --git a/src/config.rs b/src/config.rs index a7da3ab..166c80d 100644 --- a/src/config.rs +++ b/src/config.rs @@ -3,4 +3,12 @@ use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize)] pub struct Config { pub gate_open: bool +} + +impl Default for Config { + fn default() -> Self { + Self { + gate_open: false, + } + } } \ No newline at end of file