35 lines
1002 B
Rust
35 lines
1002 B
Rust
use std::{env, num::ParseIntError, path::PathBuf};
|
|
|
|
use secrecy::SecretString;
|
|
use thiserror::Error;
|
|
|
|
pub struct Config {
|
|
pub server_secret: SecretString,
|
|
pub state_dir: PathBuf,
|
|
pub port: i32,
|
|
}
|
|
|
|
#[derive(Error, Debug)]
|
|
pub enum ConfigError {
|
|
#[error("Missing SERVER_SECRET")]
|
|
MissingServerSecret,
|
|
#[error("Parse error {0}")]
|
|
InvalidPort(#[from] ParseIntError),
|
|
#[error("Unknown error: #{0}")]
|
|
Unknown(anyhow::Error),
|
|
}
|
|
|
|
impl Config {
|
|
pub fn new() -> Result<Self, ConfigError> {
|
|
dotenvy::dotenv().map_err(|err| ConfigError::Unknown(err.into()))?;
|
|
let server_secret = env::var("SERVER_SECRET").map(SecretString::from).map_err(|_| ConfigError::MissingServerSecret)?;
|
|
let state_dir = env::var("STATE_DIR").map_or_else(|_| PathBuf::from("/tmp/"), PathBuf::from);
|
|
let port = match env::var("PORT") {
|
|
Ok(p) => p.parse(),
|
|
Err(_) => Ok(3000),
|
|
}?;
|
|
Ok(Self{server_secret, state_dir, port})
|
|
}
|
|
}
|
|
|