1
Fork 0
mirror of https://github.com/redstrate/Kawari.git synced 2025-04-25 08:27:44 +00:00

Fix the admin server not creating config.json if not found

This commit is contained in:
Joshua Goins 2024-05-11 13:13:03 -04:00
parent fa6c2ddf7f
commit 0918700a85
3 changed files with 30 additions and 19 deletions

1
.gitignore vendored
View file

@ -1,2 +1,3 @@
/target /target
.idea/ .idea/
config.json

View file

@ -10,6 +10,14 @@ use axum::response::{Html, Redirect};
use axum::routing::post; use axum::routing::post;
use kawari::config::Config; 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)] #[derive(Debug, Clone, Serialize, Deserialize)]
struct GateStatus { struct GateStatus {
status: i32, status: i32,
@ -18,14 +26,9 @@ struct GateStatus {
async fn root() -> Html<String> { async fn root() -> Html<String> {
tracing::info!("Requesting gate status..."); tracing::info!("Requesting gate status...");
// read config let config = get_config();
if let Ok(data) = std::fs::read_to_string("config.json") {
let config: Config = serde_json::from_str(&data).expect("Failed to parse");
Html(format!("<p>Gate open:{}</p><form action='apply' method='post'><input type='checkbox' id='gate_open' name='gate_open' checked /><button type='submit'>Apply</button></form>", config.gate_open)) Html(format!("<p>Gate open:{}</p><form action='apply' method='post'><input type='checkbox' id='gate_open' name='gate_open' checked /><button type='submit'>Apply</button></form>", config.gate_open))
} else {
Html(format!("unknown error"))
}
} }
#[derive(Deserialize, Debug)] #[derive(Deserialize, Debug)]
@ -37,8 +40,8 @@ struct Input {
async fn apply(Form(input): Form<Input>) -> Redirect { async fn apply(Form(input): Form<Input>) -> Redirect {
tracing::info!("Apply config changes..."); tracing::info!("Apply config changes...");
if let Ok(data) = std::fs::read_to_string("config.json") { let mut config = get_config();
let mut config: Config = serde_json::from_str(&data).expect("Failed to parse");
if let Some(gate_open) = input.gate_open { if let Some(gate_open) = input.gate_open {
config.gate_open = gate_open == "on"; config.gate_open = gate_open == "on";
} else { } else {
@ -50,7 +53,6 @@ async fn apply(Form(input): Form<Input>) -> Redirect {
&config, &config,
) )
.expect("TODO: panic message"); .expect("TODO: panic message");
}
Redirect::to("/") Redirect::to("/")
} }

View file

@ -4,3 +4,11 @@ use serde::{Deserialize, Serialize};
pub struct Config { pub struct Config {
pub gate_open: bool pub gate_open: bool
} }
impl Default for Config {
fn default() -> Self {
Self {
gate_open: false,
}
}
}