use json::{JsonValue, object};
#[derive(Clone, Debug)]
pub struct Config {
pub debug: bool,
pub url: String,
pub host: String,
pub port: String,
pub public: String,
pub runtime: String,
pub schema: String,
pub ssl: bool,
pub ssl_pkey: String,
pub ssl_certs: String,
pub cors: Cors,
pub log: bool,
pub root_dir: String,
}
impl Config {
pub fn default() -> Self {
Self {
url: "".to_string(),
host: "0.0.0.0".to_string(),
port: "3535".to_string(),
public: "public".to_string(),
runtime: "runtime".to_string(),
cors: Cors::default(),
ssl: false,
ssl_pkey: "".to_string(),
ssl_certs: "".to_string(),
debug: false,
schema: "http".to_string(),
log: true,
root_dir: String::new(),
}
}
pub fn from(data: JsonValue) -> Self {
let schema = if data["ssl"].as_bool().unwrap_or(false) {
"https"
} else {
"http"
};
Self {
host: data["host"].as_str().unwrap_or("").to_string(),
port: data["port"].to_string(),
url: "".to_string(),
public: data["public"].as_str().unwrap_or("public").to_string(),
runtime: data["runtime"].as_str().unwrap_or("runtime").to_string(),
cors: Cors::from(data["cors"].clone()),
ssl: data["ssl"].as_bool().unwrap_or(false),
ssl_pkey: data["ssl_pkey"].as_str().unwrap_or("").to_string(),
ssl_certs: data["ssl_certs"].as_str().unwrap_or("").to_string(),
debug: data["debug"].as_bool().unwrap_or(false),
schema: schema.to_string(),
log: data["log"].as_bool().unwrap_or(true),
root_dir: data["root_dir"].as_str().unwrap_or("").to_string(),
}
}
pub fn json(self) -> JsonValue {
object! {
host:self.host,
port:self.port,
public:self.public,
runtime:self.runtime,
cors:self.cors.json(),
ssl:self.ssl,
ssl_pkey:self.ssl_pkey,
ssl_certs:self.ssl_certs,
debug:self.debug,
log:self.log,
}
}
}
#[derive(Clone, Debug)]
pub struct Cors {
pub allow_origin: Vec<String>,
pub allow_methods: String,
pub allow_headers: String,
pub allow_credentials: bool,
pub expose_headers: String,
pub max_age: i32,
}
impl Cors {
pub fn default() -> Self {
Self {
allow_origin: vec![],
allow_methods: "GET,POST".to_string(),
allow_headers: "content-type,X-Requested-With,x-api,x-token,x-mode".to_string(),
allow_credentials: true,
expose_headers: "content-disposition".to_string(),
max_age: 86400,
}
}
pub fn json(self) -> JsonValue {
let res = format!("{:?}", self);
let res = res.replace("Cors {", "{");
let res = res.replace(",},", "}");
let res = res.replace(": ", "\": ");
let res = res.replace("{ ", "{ \"");
let res = res.replace(", ", ", \"");
json::parse(&res).unwrap()
}
pub fn from(data: JsonValue) -> Self {
Self {
allow_origin: data["allow_origin"].members().map(|x| x.to_string()).collect(),
allow_methods: data["allow_methods"].to_string(),
allow_headers: data["allow_headers"].to_string(),
allow_credentials: data["allow_credentials"].as_bool().unwrap_or(true),
expose_headers: data["expose_headers"].to_string(),
max_age: data["max_age"].as_i32().unwrap_or(86400),
}
}
}