1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
use std::fs;
use json::{JsonValue, object};


#[cfg(any(feature = "server"))]
use crate::server::{Handler, Server};

#[cfg(any(feature = "server"))]
pub mod server;

/// 请求
#[cfg(any(feature = "server"))]
pub mod request;
/// 响应
#[cfg(any(feature = "server"))]
pub mod response;

#[cfg(any(feature = "server"))]
pub fn listen(path: &str, factory: fn() -> Box<dyn Handler>) {
    loop {
        fn default(path: &str) -> JsonValue {
            let _ = fs::create_dir(path);
            let conf = Config::default();
            let _ = fs::write(&*path, &*conf.clone().to_json().to_string());
            conf.to_json()
        }
        let config = match fs::read_to_string(path) {
            Ok(content) => {
                match json::parse(content.as_str()) {
                    Ok(e) => e,
                    Err(_) => default(path)
                }
            }
            Err(_) => default(path)
        };
        let config = Config::load(config);
        let mut web = Server::new(config.clone(), factory);
        web.listen();
    }
}
#[derive(Clone, Debug)]
pub struct Config {
    /// 域名
    pub domain: String,
    /// 服务器地址
    pub url: String,
    /// 服务器ip
    pub ip: String,
    /// 服务器端口
    pub port: String,
    /// 对外访问目录
    pub public: String,
    /// 运行目录
    pub runtime: String,
    /// 跨域请求配置
    pub cors: Cors,
    /// 安全协议
    pub ssl: bool,
    /// 私钥文件
    pub ssl_pkey: String,
    /// 公钥文件
    pub ssl_certs: String,
    /// 开启调试
    pub debug: bool,
}

impl Config {
    /// 默认
    pub fn default() -> Self {
        Self {
            domain: "".to_string(),
            url: "".to_string(),
            ip: "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,
        }
    }
    /// 加载数据
    pub fn load(data: JsonValue) -> Self {
        Self {
            domain: data["domain"].to_string(),
            url: "".to_string(),
            ip: data["ip"].to_string(),
            port: data["port"].to_string(),
            public: data["public"].to_string(),
            runtime: data["runtime"].to_string(),
            cors: Cors::load(data["cors"].clone()),
            ssl: data["ssl"].as_bool().unwrap_or(false),
            ssl_pkey: data["ssl_pkey"].to_string(),
            ssl_certs: data["ssl_certs"].to_string(),
            debug: data["debug"].as_bool().unwrap_or(false),
        }
    }
    pub fn to_json(self) -> JsonValue {
        let mut data = object! {};
        data["domain"] = self.domain.into();
        data["ip"] = self.ip.into();
        data["port"] = self.port.into();
        data["public"] = self.public.into();
        data["runtime"] = self.runtime.into();
        data["ssl"] = self.ssl.into();
        data["ssl_pkey"] = self.ssl_pkey.into();
        data["ssl_certs"] = self.ssl_certs.into();
        data["cors"] = self.cors.to_json();
        data["debug"] = self.debug.into();
        data
    }
}


/// 跨域资源共享
#[derive(Clone, Debug)]
pub struct Cors {
    /// 源
    pub allow_origin: Vec<String>,
    /// 请求中可以使用那些请求方法
    pub allow_methods: String,
    /// 请求中可以使用那些
    pub(crate) allow_headers: String,
    /// 响应暴露给前端 JavaScript
    pub allow_credentials: bool,
    /// 跨域请求请求头中允许携带的除Cache-Controller、Content-Language、Content-Type、Expires、Last-Modified、Pragma这六个基本字段之外的其他字段信息
    pub expose_headers: String,
    /// 准备响应前的缓存持续的最大时间(以秒为单位,目的是减少浏览器预检请求/响应交互的数量。默认值1800s。设置了该值后,浏览器将在设置值的时间段内对该跨域请求不再发起预请求
    pub max_age: i32,
}

impl Cors {
    /// 默认
    pub fn default() -> Self {
        Self {
            allow_origin: vec![],
            allow_methods: "GET,POST".to_string(),
            allow_headers: "content-type".to_string(),
            allow_credentials: true,
            expose_headers: "content-disposition".to_string(),
            max_age: 1800,
        }
    }
    /// 转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["expose_headers"] = self.expose_headers.into();
        data["max_age"] = self.max_age.into();
        data
    }
    pub fn load(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(1800),
        }
    }
}


#[derive(Clone, Debug)]
pub enum ContentType {
    Xml,
    Html,
    Json,
    FormData,
    XWwwFormUrlencoded,
    Plain,
    JavaScript,
    None,
}

impl ContentType {
    pub fn form(text: &str) -> Self {
        match text {
            "text/html" => ContentType::Html,
            "text/xml" | "application/xml" => ContentType::Xml,
            "text/plain" => ContentType::Plain,
            "application/json" => ContentType::Json,
            "application/javascript" => ContentType::JavaScript,
            "multipart/form-data" => ContentType::FormData,
            "application/x-www-form-urlencoded" => ContentType::XWwwFormUrlencoded,
            _ => ContentType::None
        }
    }
    pub fn to_str(self) -> &'static str {
        match self {
            ContentType::Html => "text/html",
            ContentType::Plain => "text/plain",
            ContentType::Xml => "application/xml",
            ContentType::Json => "application/json",
            ContentType::JavaScript => "application/javascript",
            ContentType::FormData => "multipart/form-data",
            ContentType::XWwwFormUrlencoded => "application/x-www-form-urlencoded",
            ContentType::None => ""
        }
    }
}