df-web 0.1.28

This is an WEB SERVER
Documentation
use json::{JsonValue, object};

/// 跨域
#[derive(Clone, Debug)]
pub struct Cors {
    pub(crate) allow_origin: String,
    pub(crate) allow_methods: String,
    pub(crate) allow_headers: String,
    pub(crate) allow_credentials: bool,
    pub(crate) max_age: i32,
}

impl Cors {
    /// 默认
    pub fn default() -> Self {
        Self {
            allow_origin: "*".to_string(),
            allow_methods: "*".to_string(),
            allow_headers: "*".to_string(),
            allow_credentials: true,
            max_age: 0,
        }
    }
    /// 设置限制域名
    pub fn allow_origin(mut self, origin: &str) -> Self {
        self.allow_origin = origin.to_string();
        self
    }

    /// 设置请求类型
    pub fn allow_methods(mut self, methods: &str) -> Self {
        self.allow_methods = methods.to_string();
        self
    }
    /// 设置请求头允许的字段
    pub fn allow_headers(mut self, headers: &str) -> Self {
        self.allow_headers = headers.to_string();
        self
    }
    /// 设置请求头允许Cookie
    pub fn allow_credentials(mut self, open: bool) -> Self {
        self.allow_credentials = open;
        self
    }
    /// 设置缓存周期
    pub fn max_age(mut self, int: i32) -> Self {
        self.max_age = int;
        self
    }
    /// 转JSONValue
    pub fn to_json(self) -> JsonValue {
        let mut data = object! {};
        data["allow_origin"] = self.allow_origin.into();
        data["allow_methods"] = self.allow_methods.into();
        data["allow_headers"] = self.allow_headers.into();
        data["allow_credentials"] = self.allow_credentials.into();
        data["max_age"] = self.max_age.into();
        data
    }
    pub fn load(data: JsonValue) -> Self {
        Self {
            allow_origin: data["allow_origin"].to_string(),
            allow_methods: data["allow_methods"].to_string(),
            allow_headers: data["allow_headers"].to_string(),
            allow_credentials: data["allow_credentials"].as_bool().unwrap(),
            max_age: data["max_age"].as_i32().unwrap_or(10000),
        }
    }
}