br-web 0.6.0

This is an WEB SERVER
Documentation
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
use std::{fs, thread};
use std::fs::OpenOptions;
use std::io::Write;
use std::str::Lines;
use std::time::{Duration, UNIX_EPOCH};
use chrono::{DateTime, Local};
use json::{array, JsonValue, object};
use log::{debug, error, info};
use crate::config::Config;
use crate::content_type::ContentType;

/// 请求处理
#[derive(Clone, Debug)]
pub struct Request {
    pub config: Config,
    /// 协议版本
    pub protocol: Protocol,

    /// 当前请求类型
    pub method: Method,
    /// 请求地址
    pub uri: String,
    /// 应用名称
    pub app: String,

    /// 请求时间戳
    pub timestamp: f64,
    /// 当前时间
    pub datetime: String,

    /// 服务器IP
    pub server_ip: String,
    /// 客户端IP
    pub client_ip: String,
    /// 代理IP
    pub agent_ip: String,

    /// 请求源
    pub origin: String,
    /// 当前访问域名或者IP 主机和端口号 头域
    pub host: String,
    /// 浏览器对响应的处理方式
    sec_fetch_dest: SecFetchDest,
    /// 浏览器请求模式
    sec_fetch_mode: SecFetchMode,
    /// 浏览器请求的上下文环境
    sec_fetch_site: SecFetchSite,
    /// 连接方式
    pub connection: Connection,
    /// 客户端类型
    pub user_agent: String,
    /// 客户端接受类型
    pub accept: String,
    /// 客户端接受加密
    pub accept_encoding: String,
    /// 客户端接受语言
    pub accept_language: String,
    /// 缓存机制
    pub cache_control: String,
    /// 请求内容的长度
    pub content_length: usize,
    /// 请求消息体长度
    pub content_body_length: usize,
    /// 消息体
    pub body: Vec<u8>,
    /// 来源于
    pub referer: String,
    /// 请求类型
    pub content_type: RequestContentType,
    /// 分界线
    pub boundary: String,
    /// 自定义参数
    pub custom: JsonValue,
    /// 路径
    pub path: String,
    /// 查询条件
    pub query: String,
    pub post: JsonValue,
    pub text: String,
    pub html: String,
    pub get: JsonValue,

    pub files: JsonValue,
    /// 认证模式
    pub authorization_mode: String,
    pub authorization_user: String,
    pub authorization_pass: String,
    pub authorization_token: String,
    pub authorization_data: String,
    /// 是否有源
    pub is_origin: bool,

    /// websocket
    pub upgrade: String,
    /// websocket 密钥
    pub sec_web_socket_key: String,
    /// websocket 版本
    pub sec_web_socket_version: String,
}

impl Request {
    pub fn new(config: Config, data: Vec<u8>) -> Result<Self, String> {
        let (header, body) = if let Some(index) = data.windows(4).position(|window| window == [13, 10, 13, 10]) {
            (data[..index].to_vec(), data[index + 4..].to_vec())
        } else {
            return Err("未找到消息头".to_string());
        };
        let header = unsafe { String::from_utf8_unchecked(header) };
        if config.debug {
            debug!("{:#}",header);
        }
        let mut data = header.lines();

        let header_line = data.next().unwrap_or("");
        let parts = header_line.split_whitespace().collect::<Vec<&str>>();
        if parts.len() != 3 {
            return Err(format!("非法请求: {}", header_line));
        }


        let method = Method::from(parts[0]);
        let mut uri = br_crypto::encoding::urlencoding_decode(parts[1]);
        if !uri.starts_with("/") {
            uri = format!("/{}", uri.clone());
        }
        let protocol = Protocol::from(parts[2]);

        let timestamp = Local::now().timestamp_millis() as f64 / 1000.0;
        let d = UNIX_EPOCH + Duration::from_secs(timestamp as u64);
        let datetime = DateTime::<Local>::from(d);
        let datetime = datetime.format("%Y-%m-%d %H:%M:%S").to_string();

        let mut request = Self {
            config: config.clone(),
            timestamp,
            datetime,
            protocol,
            method,
            uri,
            server_ip: "".to_string(),
            client_ip: "".to_string(),
            agent_ip: "".to_string(),
            origin: "".to_string(),
            host: "".to_string(),
            sec_fetch_dest: SecFetchDest::None,
            sec_fetch_mode: SecFetchMode::None,
            sec_fetch_site: SecFetchSite::None,
            connection: Connection::None,
            user_agent: "".to_string(),
            accept: "".to_string(),
            accept_encoding: "".to_string(),
            accept_language: "".to_string(),
            cache_control: "".to_string(),
            content_length: 0,
            content_body_length: body.len(),
            body,
            referer: "".to_string(),
            content_type: RequestContentType::None,
            boundary: "".to_string(),
            custom: object! {},
            path: "".to_string(),
            query: "".to_string(),
            post: object! {},
            text: "".to_string(),
            html: "".to_string(),
            get: object! {},
            files: object! {},
            authorization_mode: "".to_string(),
            authorization_user: "".to_string(),
            authorization_pass: "".to_string(),
            authorization_token: "".to_string(),
            is_origin: false,
            app: "".to_string(),
            authorization_data: "".to_string(),
            sec_web_socket_key: "".to_string(),
            upgrade: "".to_string(),
            sec_web_socket_version: "".to_string(),
        };
        request.header(data);
        Ok(request)
    }
    pub fn json(&mut self) -> JsonValue {
        let mut res = object! {};
        res["protocol"] = self.protocol.str().into();
        res["method"] = self.method.clone().str().into();
        res["timestamp"] = self.timestamp.into();
        res["datetime"] = self.datetime.clone().into();

        res["schema"] = self.config.schema.clone().into();
        // 插件库之后替换为url
        res["domain"] = self.config.url.clone().into();
        res["url"] = self.config.url.clone().into();

        res["uri"] = self.uri.clone().into();
        res["app"] = self.app.clone().into();

        res["origin"] = self.origin.clone().into();
        res["host"] = self.host.clone().into();
        res["user_agent"] = self.user_agent.clone().into();
        res["content_type"] = self.content_type.clone().str().into();
        res["content_length"] = self.content_length.into();

        res["server_ip"] = self.server_ip.clone().into();
        res["client_ip"] = self.client_ip.clone().into();
        res["agent_ip"] = self.agent_ip.clone().into();

        res["path"] = self.path.clone().into();
        res["query"] = self.query.clone().into();

        res["custom"] = self.custom.clone();
        res["post"] = self.post.clone();
        res["get"] = self.get.clone();
        res["text"] = self.text.clone().into();
        res["html"] = self.html.clone().into();
        res["files"] = self.files.clone();

        res["authorization_mode"] = self.authorization_mode.clone().into();
        res["authorization_user"] = self.authorization_user.clone().into();
        res["authorization_pass"] = self.authorization_pass.clone().into();
        res["authorization_token"] = self.authorization_token.clone().into();
        res["authorization_data"] = self.authorization_data.clone().into();

        res["public"] = self.config.public.clone().into();
        res["runtime"] = self.config.runtime.clone().into();

        if self.config.debug {
            res["sec-fetch-dest"] = self.sec_fetch_dest.str().into();
            res["sec-fetch-mode"] = self.sec_fetch_mode.str().into();
            res["sec-fetch-site"] = self.sec_fetch_site.str().into();
            res["accept-language"] = self.accept_language.clone().into();
            res["connection"] = self.connection.str().into();
        }
        res
    }
    pub fn header(&mut self, data: Lines) -> &mut Self {
        for text in data {
            let (key, value) = match text.trim().find(":") {
                None => {
                    continue;
                }
                Some(e) => {
                    let key = text[..e].trim().to_lowercase().clone();
                    let value = text[e + 1..].trim().to_string();
                    (key, value)
                }
            };
            match key.as_str() {
                "host" => self.host = value,
                "sec-fetch-site" => self.sec_fetch_site = SecFetchSite::from(&value),
                "sec-fetch-mode" => self.sec_fetch_mode = SecFetchMode::from(&value),
                "sec-fetch-dest" => self.sec_fetch_dest = SecFetchDest::from(&value),
                "connection" => self.connection = Connection::from(&value),
                "user-agent" => self.user_agent = value,

                "accept" => self.accept = value,
                "accept-language" => {
                    let language = value.split(",").collect::<Vec<&str>>();
                    if language.len() > 1 {
                        self.accept_language = language[0].to_string();
                    } else {
                        self.accept_language = value;
                    }
                }
                "accept-encoding" => self.accept_encoding = value.split(",").collect::<Vec<&str>>().join(";"),

                "cache-control" => self.cache_control = value,
                "content-type" => {
                    match value {
                        _ if value.contains("multipart/form-data") => {
                            let boundary: Vec<&str> = value.split("boundary=").collect();
                            self.boundary = boundary[1..].join("").to_string();
                            self.content_type = RequestContentType::from("multipart/form-data");
                        }
                        _ => {
                            self.content_type = RequestContentType::from(value.as_str());
                        }
                    }
                }
                "content-length" => self.content_length = value.parse::<usize>().unwrap_or(0),
                "origin" => self.origin = value,
                "referer" => self.referer = value,
                "authorization" => {
                    let authorization = value.split_whitespace().collect::<Vec<&str>>();
                    self.authorization_mode = authorization[0].to_lowercase();
                    match self.authorization_mode.as_str() {
                        "basic" => {
                            let text = br_crypto::base64::decode(authorization[1]);
                            let text: Vec<&str> = text.split(":").collect();
                            self.authorization_user = text[0].to_string();
                            self.authorization_pass = text[1].to_string();
                        }
                        "bearer" => {
                            self.authorization_token = authorization[1].to_string();
                        }
                        _ => {
                            self.authorization_data = authorization[1..].concat();
                        }
                    }
                }
                "sec-websocket-key" => {
                    self.sec_web_socket_key = value;
                }
                "sec_websocket_version" => {
                    self.sec_web_socket_version = value;
                }
                "upgrade" => {
                    self.upgrade = value;
                }
                _ => {
                    if !key.starts_with("x-") {
                        continue;
                    }
                    match &key[2..] {
                        "real-ip" => {
                            self.client_ip = value;
                        }
                        // 代理IP
                        "forwarded-for" => {
                            self.agent_ip = value;
                        }
                        _ => {
                            self.custom[&key[2..]] = value.into();
                        }
                    }
                }
            }
        }
        self.query();
        self
    }
    fn query(&mut self) {
        let mut uri = self.uri.clone();
        match uri.find("?") {
            None => {}
            Some(e) => {
                let query = uri[e + 1..].to_string();
                uri = uri[..e].to_string();
                self.query = query.clone();
                let params = if query.contains("&") {
                    query.split("&").collect::<Vec<&str>>()
                } else {
                    vec![query.as_str()]
                };
                for param in params {
                    let res = param.split("=").collect::<Vec<&str>>();
                    let key = res[0];
                    let value = res[1..].concat();
                    let key = br_crypto::encoding::urlencoding_decode(key);
                    let value = br_crypto::encoding::urlencoding_decode(value.as_str());
                    self.get[key] = value.into();
                }
            }
        }
        self.path = uri.clone();
        let apps = self.path.split("/").collect::<Vec<&str>>();
        self.app = if !apps.is_empty() {
            apps[1].to_string()
        } else {
            "api".to_string()
        };
    }
    /// 请求日志记录
    pub(crate) fn record_log(&mut self) {
        let text = format!("[{}] client-ip: {} agent_ip: {} content-type: {} content-length: {} {} {} {}\r\n",
                           self.datetime.clone(),
                           self.client_ip.clone(),
                           self.agent_ip.clone(),
                           self.content_type.clone().str(),
                           self.content_length.clone(),
                           self.method.clone().str(), self.protocol.str(), self.uri
        );
        let dir_path = format!("{}/log/{}", self.config.runtime, self.datetime[0..10].replace("-", "/"));
        let path = format!("{}/{}.log", dir_path.clone(), &self.datetime[11..13]);
        let debug = self.config.debug;
        thread::spawn(move || {
            let path_new = path.clone();
            match fs::create_dir_all(dir_path.clone()) {
                Ok(_) => {}
                Err(e) => {
                    if debug {
                        return error!("创建日志目录失败: {} {}",dir_path.clone(),e.to_string());
                    }
                    return;
                }
            };
            match OpenOptions::new()
                .read(true)

                .create(true)
                .append(true)
                .open(path_new.clone()) {
                Ok(mut file) => {
                    let _ = file.write_all(text.as_bytes());
                }
                Err(_) => {
                    if debug {
                        error!("日志写入失败: {}",path_new.clone())
                    }
                }
            }
        });
    }
    pub fn body(&mut self) -> Result<(), String> {
        if self.content_length > self.content_body_length {
            return Err(format!("消息长度错误: {}/{}", self.content_body_length, self.content_length));
        }
        match self.content_type {
            RequestContentType::FormData => {
                let request = unsafe { String::from_utf8_unchecked(self.body.clone()) };
                let mut request = request.trim_end_matches(format!("--{}--\r\n", self.boundary).as_str()).split(format!("--{}\r\n", self.boundary).as_str()).collect::<Vec<&str>>();
                request.remove(0);
                for item in request.iter_mut() {
                    if item.contains("filename=") {
                        let text: Vec<&str> = item.split("\r\n\r\n").collect();
                        let temp = if text.len() > 2 {
                            text[1..].join("\r\n\r\n")
                        } else {
                            text[1].to_string()
                        };
                        let body = match temp.strip_suffix("\r\n") {
                            None => temp.as_str(),
                            Some(v) => v
                        };
                        let text: Vec<&str> = text[0].split("\r\n").collect();
                        let name: Vec<&str> = text[0].split("\"").collect();
                        let types: Vec<&str> = text[1].split(": ").collect();
                        let accept = types[1];
                        let field = name[1];
                        let filename = name[3];

                        let mut file_data = object! {};
                        file_data["accept"] = accept.into();
                        file_data["name"] = filename.into();
                        file_data["md5"] = br_crypto::hash::str_to_md5(body).into();
                        file_data["suffix"] = ContentType::from(accept).suffix.into();
                        file_data["types"] = ContentType::from_suffix(file_data["suffix"].as_str().unwrap()).suffix_type_name().into();
                        file_data["size"] = body.len().into();
                        file_data["data"] = br_crypto::base64::encode_file(body.as_bytes().into()).into();
                        if self.files[field].is_empty() {
                            self.files[field] = array![file_data.clone()];
                        } else {
                            self.files[field].push(file_data.clone()).unwrap();
                        }
                    } else {
                        let re = item.split("\r\n\r\n").collect::<Vec<&str>>();
                        let name = re[0].trim_end_matches("\"").split("name=\"").collect::<Vec<&str>>();
                        self.post[name[1]] = re[1].trim_end_matches("\r\n").into();
                    }
                }
            }
            RequestContentType::FOrmUrlencoded => {
                let request = unsafe { String::from_utf8_unchecked(self.body.clone()) };
                let params = if request.contains("&") {
                    request.split("&").collect::<Vec<&str>>()
                } else {
                    vec![request.as_str()]
                };
                for param in params {
                    let res = param.split("=").collect::<Vec<&str>>();
                    let key = res[0];
                    let value = res[1..].concat();
                    let key = br_crypto::encoding::urlencoding_decode(key);
                    let value = br_crypto::encoding::urlencoding_decode(value.as_str());
                    self.post[key] = value.into();
                }
            }
            RequestContentType::Javascript => {
                let request = unsafe { String::from_utf8_unchecked(self.body.clone()) };
                if self.config.debug {
                    info!("Javascript: {}", request);
                }
            }
            RequestContentType::Json => {
                let request = unsafe { String::from_utf8_unchecked(self.body.clone()) };
                match json::parse(request.as_str()) {
                    Ok(e) => {
                        self.post = e;
                    }
                    Err(_) => {
                        error!("解析json失败,请检查格式:{}", request);
                        self.post = object! {}
                    }
                };
            }
            RequestContentType::Xml => {
                let request = unsafe { String::from_utf8_unchecked(self.body.clone()) };
                let res = br_xml::Xml::xml_json(request);
                self.post = res;
            }
            RequestContentType::Text => {
                let request = unsafe { String::from_utf8_unchecked(self.body.clone()) };
                self.text = request;
            }
            RequestContentType::Html => {
                let request = unsafe { String::from_utf8_unchecked(self.body.clone()) };
                self.html = request;
            }
            RequestContentType::None => {
                let request = unsafe { String::from_utf8_unchecked(self.body.clone()) };
                if self.config.debug {
                    info!("RequestContentType 未知: {}", request);
                }
            }
        }
        Ok(())
    }

    /// 源判断
    pub(crate) fn allow_origin(&mut self) {
        self.is_origin = false;
        if !self.config.cors.allow_origin.is_empty() {
            if self.origin.is_empty() {
                for origin in &self.config.cors.allow_origin {
                    if self.client_ip.contains(origin) {
                        self.is_origin = true;
                    }
                }
            } else {
                for origin in &self.config.cors.allow_origin {
                    if self.origin.contains(origin) {
                        self.is_origin = true;
                    }
                }
            }
        } else {
            self.is_origin = true;
        }
    }
}

/// 浏览器的请求模式
#[derive(Clone, Debug)]
enum SecFetchSite {
    /// 一个跨域请求,即请求的目标与当前页面不具有相同的来源
    CrossSite,
    /// 请求的目标与当前页面具有相同的来源,即同源请求
    SameOrigin,
    /// 请求不是从一个受信任的网站或者内嵌资源中发起的
    None,
}

impl SecFetchSite {
    pub fn from(name: &str) -> Self {
        match name.to_lowercase().as_str() {
            "none" => Self::None,
            "cross-site" => Self::CrossSite,
            "same-origin" => Self::SameOrigin,
            _ => Self::None,
        }
    }
    pub fn str(&mut self) -> &'static str {
        match self {
            SecFetchSite::CrossSite => "cross-site",
            SecFetchSite::SameOrigin => "same-origin",
            SecFetchSite::None => "none"
        }
    }
}

/// 浏览器的请求模式
#[derive(Clone, Debug)]
enum SecFetchMode {
    /// 导航请求
    Navigate,
    /// 同源请求
    SameOrigin,
    /// 跨域请求,不需要浏览器执行跨域检查
    NoCors,
    /// 跨域请求,需要浏览器执行跨域检查
    Cors,
    /// WebSocket 连接请求
    Websocket,
    /// 未知
    None,
}

impl SecFetchMode {
    pub fn from(name: &str) -> Self {
        match name.to_lowercase().as_str() {
            "navigate" => Self::Navigate,
            "same-origin" => Self::SameOrigin,
            "no-cors" => Self::NoCors,
            "cors" => Self::Cors,
            "websocket" => Self::Websocket,
            _ => Self::None,
        }
    }
    pub fn str(&mut self) -> &'static str {
        match self {
            Self::Navigate => "navigate",
            Self::SameOrigin => "same-origin",
            Self::NoCors => "no-cors",
            Self::Cors => "cors",
            Self::Websocket => "websocket",
            Self::None => ""
        }
    }
}

/// 浏览器对响应的处理方式
#[derive(Clone, Debug)]
enum SecFetchDest {
    /// 浏览器希望接收的响应是一个文档(HTML、XML 等),通常用于页面导航或者获取页面内容的请求。
    Document,
    /// 浏览器希望接收的响应是一个图像
    Image,
    /// 浏览器希望接收的响应是媒体文件
    Media,
    /// 浏览器希望接收的响应是字体文件
    Font,
    /// 浏览器希望接收的响应是 JavaScript 脚本文件
    Script,
    /// 浏览器希望接收的响应是 CSS 样式表文件
    Css,
    /// 浏览器希望接收的响应是 PWA(渐进式 Web 应用)的清单文件
    Manifest,
    /// 浏览器希望接收的响应是 Service Worker 文件,用于支持离线缓存和推送通知等功能。
    Serviceworker,
    /// 未知
    None,
}

impl SecFetchDest {
    pub fn from(name: &str) -> Self {
        match name.to_lowercase().as_str() {
            "document" => Self::Document,
            "image" => Self::Image,
            "media" => Self::Media,
            "font" => Self::Font,
            "script" => Self::Script,
            "css" => Self::Css,
            "manifest" => Self::Manifest,
            "serviceworker" => Self::Serviceworker,
            _ => Self::None,
        }
    }
    pub fn str(&mut self) -> &'static str {
        match self {
            Self::Document => "document",
            Self::Image => "image",
            Self::Media => "media",
            Self::Font => "font",
            Self::Script => "script",
            Self::Css => "css",
            Self::Manifest => "manifest",
            Self::Serviceworker => "serviceworker",
            Self::None => ""
        }
    }
}

/// 协议
#[derive(Clone, Debug)]
pub enum Protocol {
    HTTP1_1,
    HTTP2,
    None,
}

impl Protocol {
    pub fn from(name: &str) -> Self {
        match name.to_lowercase().as_str() {
            "http/1.1" => Self::HTTP1_1,
            "http/2" => Self::HTTP2,
            _ => Self::None,
        }
    }
    pub fn str(&mut self) -> &'static str {
        match self {
            Protocol::HTTP1_1 => "HTTP/1.1",
            Protocol::HTTP2 => "HTTP/2",
            Protocol::None => ""
        }
    }
}

/// 客户端和服务器之间的连接状态
#[derive(Clone, Debug)]
pub enum Connection {
    /// 客户端希望与服务器保持持久连接,以便在未来的请求中复用同一连接,减少连接的建立和断开开销,提高性能。
    KeepAlive,
    /// 客户端希望在完成当前请求之后立即关闭与服务器的连接。这种情况通常发生在客户端只需要单个请求-响应周期的情况下。
    Close,
    Upgrade,
    None,
}

impl Connection {
    pub fn from(name: &str) -> Self {
        match name.to_lowercase().as_str() {
            "keep-alive" => Self::KeepAlive,
            "close" => Self::Close,
            "upgrade" => Self::Upgrade,
            _ => Self::None,
        }
    }
    pub fn str(&mut self) -> &'static str {
        match self {
            Self::KeepAlive => "keep-alive",
            Self::Close => "close",
            Self::Upgrade => "upgrade",
            Self::None => ""
        }
    }
}

/// 请求方法
#[derive(Clone, Debug)]
pub enum Method {
    POST,
    GET,
    HEAD,
    PUT,
    DELETE,
    OPTIONS,
    PATCH,
    TRACE,
    None,
}

impl Method {
    pub fn from(name: &str) -> Self {
        match name.to_lowercase().as_str() {
            "post" => Self::POST,
            "get" => Self::GET,
            "head" => Self::HEAD,
            "put" => Self::PUT,
            "delete" => Self::DELETE,
            "options" => Self::OPTIONS,
            "patch" => Self::PATCH,
            "trace" => Self::TRACE,
            _ => Self::None,
        }
    }
    pub fn str(self) -> &'static str {
        match self {
            Method::POST => "post",
            Method::GET => "get",
            Method::HEAD => "head",
            Method::PUT => "put",
            Method::DELETE => "delete",
            Method::OPTIONS => "options",
            Method::PATCH => "patch",
            Method::TRACE => "trace",
            Method::None => ""
        }
    }
}

#[derive(Clone, Debug)]
pub enum RequestContentType {
    FormData,
    FOrmUrlencoded,
    Json,
    Xml,
    Javascript,
    Text,
    Html,
    None,
}

impl RequestContentType {
    pub fn from(name: &str) -> Self {
        match name {
            "multipart/form-data" => Self::FormData,
            "application/x-www-form-urlencoded" => Self::FOrmUrlencoded,
            "application/json" => Self::Json,
            "application/xml" | "text/xml" => Self::Xml,
            "application/javascript" => Self::Javascript,
            "text/html" => Self::Html,
            "text/plain" => Self::Text,
            _ => {
                info!("未知请求类型: {}", name);
                Self::None
            }
        }
    }
    pub fn str(self) -> &'static str {
        match self {
            RequestContentType::FormData => "multipart/form-data",
            RequestContentType::FOrmUrlencoded => "application/x-www-form-urlencoded",
            RequestContentType::Json => "application/json",
            RequestContentType::Xml => "application/xml",
            RequestContentType::Javascript => "application/javascript",
            RequestContentType::Text => "text/plain",
            RequestContentType::Html => "text/html",
            RequestContentType::None => ""
        }
    }
}