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

83 lines
2.5 KiB
Rust
Raw Normal View History

2023-07-02 05:39:35 +00:00
use std::{collections::HashMap, path::PathBuf};
2023-07-02 06:00:19 +00:00
use http::StatusCode;
use serde::{Deserialize, Serialize};
2023-08-19 01:20:53 +00:00
use crate::{http_response::HttpResponse, utils::gen_true};
2023-07-02 06:00:19 +00:00
#[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>,
2023-07-02 05:46:36 +00:00
#[serde(default = "Vec::default")]
2023-07-02 05:39:35 +00:00
pub try_templates: Vec<String>,
2023-07-02 05:46:36 +00:00
#[serde(default = "Vec::default")]
2023-07-02 05:39:35 +00:00
pub try_data: Vec<String>,
2023-07-02 05:46:36 +00:00
#[serde(default = "HashMap::default")]
2023-07-02 05:39:35 +00:00
pub datum_extension_parser: HashMap<String, DatumExtensionParser>,
2023-08-09 13:03:07 +00:00
#[serde(default = "bool::default")]
pub is_on_dev: bool,
2023-08-19 01:20:53 +00:00
#[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,
2023-07-02 05:39:35 +00:00
}
#[derive(Clone, Copy, Deserialize, Serialize, Debug)]
pub enum DatumExtensionParser {
#[serde(rename = "json")]
Json,
#[serde(rename = "yaml")]
Yaml,
2023-07-02 23:37:47 +00:00
}
impl DatumExtensionParser {
2023-08-12 20:26:47 +00:00
// 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> {
2023-07-02 23:37:47 +00:00
match self {
DatumExtensionParser::Json => {
2023-08-12 20:26:47 +00:00
serde_json::from_str::<T>(s).map_err(|e| format!("{:?}", e))
2023-07-02 23:37:47 +00:00
}
DatumExtensionParser::Yaml => {
2023-08-12 20:26:47 +00:00
serde_yaml::from_str::<T>(s).map_err(|e| format!("{:?}", e))
2023-07-02 23:37:47 +00:00
}
}
}
2023-07-01 22:10:08 +00:00
}
2023-07-02 06:00:19 +00:00
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,
2023-08-09 22:51:49 +00:00
false,
2023-07-02 06:00:19 +00:00
)
})
.ok()
}
}