contact-form/src/config.rs

44 lines
1.1 KiB
Rust
Raw Normal View History

2022-10-29 17:09:56 +00:00
use anyhow::{Context, Result};
2022-10-28 22:41:02 +00:00
use serde::Deserialize;
use std::env;
use std::fs::File;
use std::io::BufReader;
#[derive(Deserialize)]
pub struct EmailServer {
pub server_name: String,
pub email: String,
pub password: String,
}
#[derive(Deserialize)]
pub struct Address {
pub name: String,
pub user: String,
pub domain: String,
}
#[derive(Deserialize)]
pub struct Config {
pub path_prefix: String,
pub email_server: EmailServer,
pub email_from: Address,
pub email_to: Address,
}
impl Config {
2022-10-29 17:09:56 +00:00
pub fn new() -> Result<Self> {
2022-10-28 22:41:02 +00:00
let config_file_var = "CF_CONFIG_FILE";
let config_path = env::var(config_file_var)
2022-10-29 17:09:56 +00:00
.with_context(|| format!("Environment variable {config_file_var} missing!"))?;
2022-10-28 22:41:02 +00:00
2022-10-29 17:09:56 +00:00
let config_file = File::open(&config_path)
.with_context(|| format!("Can not open the config file at the path {config_path}"))?;
2022-10-28 22:41:02 +00:00
let config_reader = BufReader::new(config_file);
2022-10-29 17:09:56 +00:00
let config: Self = serde_json::from_reader(config_reader)
.context("Can not parse the config file as JSON!")?;
2022-10-28 22:41:02 +00:00
2022-10-29 17:09:56 +00:00
Ok(config)
2022-10-28 22:41:02 +00:00
}
}