Created
May 18, 2024 17:31
-
-
Save HeCorr/8a347f96a63082b0da0607a03ceb1e83 to your computer and use it in GitHub Desktop.
Basic Rust TOML Config Handler
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# cargo add serde toml | |
pub mod config { | |
use serde::{Deserialize, Serialize}; | |
use std::{fs, path::Path}; | |
#[derive(Serialize, Deserialize)] | |
pub struct Config { | |
pub version: i8, | |
pub host: String, | |
pub port: u32, | |
pub root: String, | |
} | |
impl Default for Config { | |
fn default() -> Self { | |
Self { | |
version: 1, | |
host: String::from("localhost"), | |
port: 3032, | |
root: String::from("/var/www/html"), | |
} | |
} | |
} | |
impl Config { | |
/// Config file path | |
fn path() -> &'static str { | |
"config.toml" | |
} | |
/// Initializes a new Config. | |
/// | |
/// If a config file exists, it is read and returned. | |
/// If it does not, a new one is created with default options and returned. | |
pub fn new() -> Config { | |
let mut cfg = Config::default(); | |
let exists = Path::new(Config::path()).try_exists().unwrap(); | |
if exists { | |
cfg.read(); | |
} else { | |
cfg.write(); | |
} | |
cfg | |
} | |
/// Reads Config from file. | |
/// | |
/// Must be called after `new()` to make sure the file is initialized properly. | |
pub fn read(&mut self) { | |
let file = fs::read_to_string(Config::path()).unwrap(); | |
let config: Config = toml::from_str(&file).unwrap(); | |
*self = config; | |
} | |
/// Writes Config to a file. | |
pub fn write(&self) { | |
let config = toml::to_string(&self).unwrap(); | |
fs::write(Config::path(), config).unwrap(); | |
} | |
} | |
} | |
#[cfg(test)] | |
mod config_test { | |
use crate::config::Config; | |
#[test] | |
fn config_example() { | |
// warning: this may panic as I haven't implemented error handling at all. | |
let mut cfg = Config::new(); | |
println!( | |
"Version: {}\nHost: {}\nPort: {}\nRoot: {}", | |
cfg.version, cfg.host, cfg.port, cfg.root | |
); | |
cfg.host = String::from("127.0.0.1"); | |
cfg.write(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment