static-site-server-rs/src/server_config.rs

83 lines
2.5 KiB
Rust

use std::{collections::HashMap, path::PathBuf};
use http::StatusCode;
use serde::{Deserialize, Serialize};
use crate::{http_response::HttpResponse, utils::gen_true};
#[derive(Clone, Deserialize, Serialize, Debug)]
pub struct ServerConfig {
pub threads: usize,
pub port: u16,
pub bind: String,
pub sites: PathBuf,
pub routes: PathBuf,
pub not_found: PathBuf,
pub try_files: Vec<String>,
#[serde(default = "Vec::default")]
pub try_templates: Vec<String>,
#[serde(default = "Vec::default")]
pub try_data: Vec<String>,
#[serde(default = "HashMap::default")]
pub datum_extension_parser: HashMap<String, DatumExtensionParser>,
#[serde(default = "bool::default")]
pub is_on_dev: bool,
#[serde(default = "gen_true")]
pub log_accesses: bool,
#[serde(default = "gen_true")]
pub log_redirects: bool,
#[serde(default = "gen_true")]
pub log_not_founds: bool,
#[serde(default = "gen_true")]
pub log_server_errors: bool,
}
#[derive(Clone, Copy, Deserialize, Serialize, Debug)]
pub enum DatumExtensionParser {
#[serde(rename = "json")]
Json,
#[serde(rename = "yaml")]
Yaml,
}
impl DatumExtensionParser {
// pub fn parse_u8<'a, T: serde::de::Deserialize<'a>>(&self, s: &'a [u8]) -> Result<T, String> {
// match self {
// DatumExtensionParser::Json => {
// serde_json::from_slice::<T>(s).map_err(|e| format!("{:?}", e))
// }
// DatumExtensionParser::Yaml => {
// serde_yaml::from_slice::<T>(s).map_err(|e| format!("{:?}", e))
// }
// }
// }
pub fn parse_str<'a, T: serde::de::Deserialize<'a>>(&self, s: &'a str) -> Result<T, String> {
match self {
DatumExtensionParser::Json => {
serde_json::from_str::<T>(s).map_err(|e| format!("{:?}", e))
}
DatumExtensionParser::Yaml => {
serde_yaml::from_str::<T>(s).map_err(|e| format!("{:?}", e))
}
}
}
}
impl ServerConfig {
pub fn generate_404(&self) -> Option<HttpResponse> {
std::fs::read(self.not_found.clone())
.map(|p| {
HttpResponse::new(
StatusCode::NOT_FOUND,
p.as_slice(),
Some("text/html; charset=utf-8".to_string()),
None,
None,
false,
)
})
.ok()
}
}