br-web-server 0.5.19

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
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
#[cfg(feature = "client")]
pub mod client;
mod client_response;
pub mod config;
pub mod request;
pub mod response;
pub mod stream;
pub mod url;
pub mod websocket;

use crate::config::Config;
use crate::request::Request;
use crate::response::Response;
use crate::stream::Scheme;
use crate::websocket::{CloseCode, ErrorCode, Message, Websocket};
use fs::read;
use log::{error, info, warn};

use rustls_pemfile::certs;

use flate2::read::GzDecoder;
use flate2::write::GzEncoder;
use flate2::Compression;
use json::{object, JsonValue};
use rustls::{ServerConfig, ServerConnection, StreamOwned};
use std::fmt::Debug;
use std::io::{BufReader, Error, Read, Write};
use std::net::TcpListener;
use std::path::PathBuf;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use std::{fs, io, thread};

/// 网络服务
#[derive(Clone, Debug)]
pub struct WebServer;

struct ConnectionGuard(Arc<AtomicUsize>);

impl Drop for ConnectionGuard {
    fn drop(&mut self) {
        self.0.fetch_sub(1, Ordering::Relaxed);
    }
}

impl WebServer {
    /// 后台服务器
    pub fn new_service(config: Config, factory: fn(out: Websocket) -> Box<dyn Handler>) {
        loop {
            match WebServer::service(config.clone(), factory) {
                Ok(()) => {}
                Err(e) => error!("服务器错误: {}[{}]: {}", file!(), line!(), e),
            }
            warn!("服务器 1秒后重启");
            thread::sleep(Duration::from_secs(1));
        }
    }
    fn service(config: Config, factory: fn(out: Websocket) -> Box<dyn Handler>) -> io::Result<()> {
        info!("==================== 网络服务 服务信息 ====================");
        info!("日志记录: {}", if config.log { "开启" } else { "关闭" });
        info!("调试模式: {}", if config.debug { "开启" } else { "关闭" });
        info!("监听地址: {}", config.host);
        info!(
            "服务地址: {}://{}",
            if config.https { "https" } else { "http" },
            config.host
        );
        info!("根 目 录: {}", config.root_path.to_str().unwrap_or(""));
        info!("访问目录: {}", config.public);
        info!("运行目录: {}", config.runtime);
        info!("SSL/TLS: {}", if config.https { "开启" } else { "关闭" });

        if config.https {
            info!("证书目录KEY: {:?}", config.tls.key);
            info!("证书目录PEM: {:?}", config.tls.certs);
        }

        let listener = TcpListener::bind(config.host.clone())?;
        info!("==================== 网络服务 启动成功 ====================");

        let acceptor = Self::ssl(config.clone())?;
        let connection_count = Arc::new(AtomicUsize::new(0));
        for stream in listener.incoming() {
            match stream {
                Ok(stream) => {
                    let current = connection_count.load(Ordering::Relaxed);
                    if current >= config.max_connections {
                        warn!(
                            "连接数已达上限 ({}/{}), 拒绝新连接",
                            current, config.max_connections
                        );
                        drop(stream);
                        continue;
                    }
                    connection_count.fetch_add(1, Ordering::Relaxed);
                    let config_new = config.clone();
                    let acceptor_new = acceptor.clone();
                    let conn_count = connection_count.clone();
                    thread::spawn(move || -> io::Result<()> {
                        let _guard = ConnectionGuard(conn_count);
                        stream.set_nonblocking(false)?;
                        stream
                            .set_read_timeout(Some(Duration::from_secs(config_new.read_timeout)))
                            .unwrap_or_default();
                        stream
                            .set_write_timeout(Some(Duration::from_secs(config_new.write_timeout)))
                            .unwrap_or_default();

                        let scheme = if config_new.https {
                            let acceptor = acceptor_new
                                .ok_or_else(|| Error::other("TLS acceptor not configured"))?;
                            let conn = match ServerConnection::new(acceptor) {
                                Ok(e) => e,
                                Err(e) => {
                                    return Err(Error::other(e.to_string()));
                                }
                            };
                            Scheme::Https(Arc::new(Mutex::new(StreamOwned::new(conn, stream))))
                        } else {
                            Scheme::Http(Arc::new(Mutex::new(stream)))
                        };

                        let mut request =
                            Request::new(config_new.clone(), Arc::new(Mutex::new(scheme.clone())));
                        let response = match request.handle() {
                            Ok(()) => Response::new(&request.clone(), factory),
                            Err(e) => {
                                //error!("处理请求: {:?} {} {}",thread::current().id() ,e.code, e.body);
                                return Err(Error::other(e.body.as_str()));
                            }
                        };
                        match response.handle() {
                            Ok(()) => {}
                            Err(e) => {
                                //error!("发送错误失败2: {}",e.to_string());
                                return Err(Error::other(e));
                            }
                        };

                        match request.save_log() {
                            Ok(()) => {}
                            Err(_) => error!("日志记录错误"),
                        }
                        Ok(())
                    });
                }
                Err(e) => return Err(e),
            }
        }
        Ok(())
    }
    fn ssl(config: Config) -> io::Result<Option<Arc<ServerConfig>>> {
        if config.https {
            if !config.tls.key.is_file() {
                return Err(Error::other(
                    format!("private.key 不存在: {:?}", config.tls.key.clone()).as_str(),
                ));
            }
            if !config.tls.certs.is_file() {
                return Err(Error::other(
                    format!("certificate.pem 不存在: {:?}", config.tls.certs).as_str(),
                ));
            }
            let t = read(config.tls.key)?;
            let mut reader = BufReader::new(t.as_slice());
            let key = rustls_pemfile::private_key(&mut reader)
                .map_err(|e| Error::other(format!("failed to parse private key: {}", e)))?
                .ok_or_else(|| Error::other("no private key found in key file"))?;
            let t = read(config.tls.certs)?;
            let mut reader = BufReader::new(t.as_slice());
            let certs = certs(&mut reader)
                .collect::<Result<Vec<_>, _>>()?
                .as_slice()
                .to_owned();

            let config = match ServerConfig::builder()
                // 不需要客户端证书认证(单向 TLS),本地服务/一般 Web 服务都这么写
                .with_no_client_auth()
                // 配置“服务器证书链 + 服务器私钥”
                .with_single_cert(certs, key)
            {
                Ok(e) => e,
                Err(e) => return Err(Error::other(e)),
            };

            Ok(Some(Arc::new(config)))
            //let mut acceptor = SslAcceptor::mozilla_intermediate(SslMethod::tls())?;
            //if !config.tls.key.is_file() {
            //    return Err(Error::other(
            //        format!("private.key 不存在: {:?}", config.tls.key).as_str(),
            //    ));
            //}
            //if !config.tls.certs.is_file() {
            //    return Err(Error::other(
            //        format!("certificate.pem 不存在: {:?}", config.tls.certs).as_str(),
            //    ));
            //}
            //acceptor.set_private_key_file(config.tls.key.clone(), SslFiletype::PEM)?;
            //acceptor.set_certificate_file(config.tls.certs.clone(), SslFiletype::PEM)?;
            //Ok(Arc::new(acceptor.build()))
        } else {
            Ok(None)
        }
    }
}

pub trait HandlerClone {
    fn clone_box(&self) -> Box<dyn Handler>;
}

/// 实现 HandlerClone for 所有 Handler + Clone 的实现者
impl<T> HandlerClone for T
where
    T: 'static + Handler + Clone,
{
    fn clone_box(&self) -> Box<dyn Handler> {
        Box::new(self.clone())
    }
}

// 为 dyn Handler 实现 Clone
impl Clone for Box<dyn Handler> {
    fn clone(&self) -> Box<dyn Handler> {
        self.clone_box()
    }
}
pub trait Handler: Send + Sync + HandlerClone + Debug {
    /// 请求 处理
    fn on_request(&mut self, _request: Request, _response: &mut Response);
    /// 预检请求处理 OPTIONS
    fn on_options(&mut self, response: &mut Response) {
        response.allow_origins = vec![];
        response.allow_methods = vec!["GET", "POST", "PUT", "DELETE", "OPTIONS"];
        response.allow_headers = vec!["Authorization", "X-Forwarded-For", "X-Real-IP"];
        response.header("Access-Control-Expose-Headers", "Content-Disposition");
        response.header("Access-Control-Max-Age", 86400.to_string().as_str());
    }
    /// 响应 处理
    fn on_response(&mut self, response: &mut Response) {
        if !response.headers.has_key("Access-Control-Allow-Origin") {
            response.header("Access-Control-Allow-Origin", "*");
        }
    }

    fn on_frame(&mut self) -> Result<(), HttpError> {
        Ok(())
    }
    /// 握手监听
    fn on_open(&mut self) -> Result<(), HttpError> {
        Ok(())
    }
    /// 接收到消息
    fn on_message(&mut self, _msg: Message) -> Result<(), HttpError> {
        Ok(())
    }
    /// 关闭监听
    fn on_close(&mut self, _code: CloseCode, _reason: &str) {}
    /// 错误监听
    fn on_error(&mut self, _err: ErrorCode) {}
    /// 关机监听
    fn on_shutdown(&mut self) {}
}

#[derive(Clone, Debug)]
pub enum Connection {
    /// 长连接
    KeepAlive,
    /// 短连接
    Close,
    Other(String),
}
impl Connection {
    pub fn from(value: &str) -> Self {
        match value.to_lowercase().as_str() {
            "keep-alive" => Self::KeepAlive,
            "close" => Self::Close,
            _ => Self::Other(value.to_string()),
        }
    }
    pub fn str(&self) -> &str {
        match self {
            Connection::KeepAlive => "keep-alive",
            Connection::Close => "close",
            Connection::Other(name) => name,
        }
    }
}
#[derive(Clone, Debug)]
pub enum Upgrade {
    Websocket,
    Http,
    H2c,
    Other(String),
}
impl Upgrade {
    #[must_use]
    pub fn from(name: &str) -> Self {
        match name.to_lowercase().as_str() {
            "websocket" => Upgrade::Websocket,
            "http" => Upgrade::Http,
            "h2c" => Upgrade::H2c,
            _ => Upgrade::Other(name.to_lowercase().as_str().to_string()),
        }
    }
    #[must_use]
    pub fn str(&self) -> &str {
        match self {
            Upgrade::Websocket => "websocket",
            Upgrade::Http => "http",
            Upgrade::H2c => "h2c",
            Upgrade::Other(name) => name,
        }
    }
}

/// 统一资源标识符
#[derive(Clone, Debug, Default)]
pub struct Uri {
    /// 资源标识
    pub uri: String,
    /// 完整 url
    pub url: String,
    /// 查询字符串
    pub query: String,
    /// 片段或位置
    pub fragment: String,
    /// 资源路径
    pub path: String,
    /// 资源段落
    pub path_segments: Vec<String>,
}
impl Uri {
    #[must_use]
    pub fn from(url: &str) -> Self {
        let mut decoded_url = br_crypto::encoding::urlencoding_decode(url);
        let fragment = match decoded_url.rfind('#') {
            None => String::new(),
            Some(index) => decoded_url.drain(index..).collect::<String>(),
        };

        let query = match decoded_url.rfind('?') {
            None => String::new(),
            Some(index) => decoded_url
                .drain(index..)
                .collect::<String>()
                .trim_start_matches("?")
                .to_string(),
        };

        let path_segments = decoded_url
            .split('/')
            .map(|x| x.to_string())
            .filter(|x| !x.is_empty())
            .collect::<Vec<String>>();
        Self {
            uri: decoded_url.clone(),
            url: url.to_string(),
            query,
            fragment,
            path: decoded_url.clone(),
            path_segments,
        }
    }
    /// 获取请求参数
    #[must_use]
    pub fn get_query_params(&self) -> JsonValue {
        let text = self.query.split('&').collect::<Vec<&str>>();
        let mut params = object! {};
        for item in text {
            if let Some(index) = item.find('=') {
                let key = item[..index].to_string();
                let value = item[index + 1..].to_string();
                let _ = params.insert(key.as_str(), value);
            }
        }
        params
    }
    #[must_use]
    pub fn to_json(&self) -> JsonValue {
        object! {
            url: self.url.clone(),
            query: self.query.clone(),
            fragment: self.fragment.clone(),
            path: self.path.clone(),
            path_segments: self.path_segments.clone()
        }
    }
}

/// 请求方法
#[derive(Clone, Debug)]
pub enum Method {
    /// 请求
    POST,
    /// 获取
    GET,
    /// 请求头
    HEAD,
    /// 更新
    PUT,
    /// 删除
    DELETE,
    /// 预请求
    OPTIONS,
    PATCH,
    TRACE,
    VIEW,
    CONNECT,
    PROPFIND,
    /// http2.0
    PRI,
    /// 其他
    Other(String),
}

impl Method {
    #[must_use]
    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,
            "view" => Self::VIEW,
            "propfind" => Self::PROPFIND,
            "connect" => Self::CONNECT,
            "pri" => Self::PRI,
            _ => Self::Other(name.to_lowercase()),
        }
    }
    #[must_use]
    pub fn str(&self) -> &str {
        match self {
            Self::POST => "POST",
            Self::GET => "GET",
            Self::HEAD => "HEAD",
            Self::PUT => "PUT",
            Self::DELETE => "DELETE",
            Self::OPTIONS => "OPTIONS",
            Self::PATCH => "PATCH",
            Self::TRACE => "TRACE",
            Self::VIEW => "VIEW",
            Self::PROPFIND => "PROPFIND",
            Self::PRI => "PRI",
            Self::CONNECT => "CONNECT",
            Method::Other(e) => e.as_str(),
        }
    }
}

#[derive(Debug, Clone)]
pub struct HttpError {
    pub code: u16,
    pub body: String,
}

impl HttpError {
    /// 构造函数:用状态码和文本信息
    #[must_use]
    pub fn new(code: u16, body: &str) -> Self {
        Self {
            code,
            body: body.to_string(),
        }
    }
}
/// 内容类型
#[derive(Debug, Clone)]
pub enum ContentType {
    FormData,
    FormUrlencoded,
    Json,
    Xml,
    Javascript,
    Text,
    Html,
    Stream,
    Other(String),
}
impl ContentType {
    #[must_use]
    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,
            "application/octet-stream" => Self::Stream,
            "text/html" => Self::Html,
            "text/plain" => Self::Text,
            _ => Self::Other(name.to_string()),
        }
    }
    #[must_use]
    pub fn str(&self) -> &str {
        match self {
            ContentType::FormData => "multipart/form-data",
            ContentType::FormUrlencoded => "application/x-www-form-urlencoded",
            ContentType::Json => "application/json",
            ContentType::Xml => "application/xml",
            ContentType::Javascript => "application/javascript",
            ContentType::Text => "text/plain",
            ContentType::Html => "text/html",
            ContentType::Other(name) => name.as_str(),
            ContentType::Stream => "application/octet-stream",
        }
    }
}

/// 解析 `Content-Type` 请求头值,提取主 MIME 类型与参数(如 charset/boundary)。
///
/// - 输入示例:`application/json;charset=utf-8`、`application/json; charset=utf-8`
/// - 输入示例:`multipart/form-data;boundary=abc`、`multipart/form-data; boundary="abc"`
///
/// 返回:
/// - `mime`:主类型(已 `trim` 并 `to_lowercase`)
/// - `params`:参数表(key 已 `to_lowercase`;value 已 `trim` 并去除可选引号)
pub(crate) fn parse_content_type_header_value(
    value: &str,
) -> (String, std::collections::HashMap<String, String>) {
    let mut it = value.split(';');
    let mime = it.next().unwrap_or("").trim().to_lowercase();

    let mut params = std::collections::HashMap::<String, String>::new();
    for raw in it {
        let raw = raw.trim();
        if raw.is_empty() {
            continue;
        }
        if let Some((k, v)) = raw.split_once('=') {
            let key = k.trim().to_lowercase();
            let mut val = v.trim();
            if val.len() >= 2 && val.starts_with('"') && val.ends_with('"') {
                val = &val[1..val.len() - 1];
            }
            params.insert(key, val.to_string());
        } else {
            // 允许无值参数(极少见),保留空字符串
            params.insert(raw.to_lowercase(), String::new());
        }
    }

    (mime, params)
}
/// 认证
#[derive(Clone, Debug)]
pub enum Authorization {
    Basic(String, String),
    Bearer(String),
    Digest(JsonValue),
    Other(String),
}
impl Authorization {
    #[must_use]
    pub fn from(data: &str) -> Self {
        let authorization = data.split_whitespace().collect::<Vec<&str>>();
        let mode = authorization[0].to_lowercase();
        match mode.as_str() {
            "basic" => {
                let text = br_crypto::base64::decode(&authorization[1].to_string());
                let text: Vec<&str> = text.split(':').collect();
                Self::Basic(text[0].to_string(), text[1].to_string())
            }
            "bearer" => Self::Bearer(authorization[1].to_string()),
            "digest" => {
                let text = authorization[1..].concat().clone();
                let text = text.split(',').collect::<Vec<&str>>();
                let mut params = object! {};
                for item in &text {
                    let Some(index) = item.find('=') else {
                        continue;
                    };
                    let key = item[..index].to_string();
                    let value = item[index + 2..item.len() - 1].to_string();
                    let _ = params.insert(key.as_str(), value);
                }
                Self::Digest(params)
            }
            _ => Self::Other(data.to_string()),
        }
    }
    #[must_use]
    pub fn str(&self) -> JsonValue {
        match self {
            Self::Basic(key, value) => {
                let mut data = object! {};
                data[key.as_str()] = value.clone().into();
                data
            }
            Self::Bearer(e) => e.clone().into(),
            Self::Digest(e) => e.clone(),
            Self::Other(name) => name.clone().into(),
        }
    }
}
/// 消息内容
#[derive(Clone, Debug)]
pub enum Content {
    FormUrlencoded(JsonValue),
    FormData(JsonValue),
    Json(JsonValue),
    Text(JsonValue),
    Xml(JsonValue),
    None,
}
impl Content {}
#[derive(Clone, Debug)]
pub enum FormData {
    File(String, PathBuf),
    Field(JsonValue),
}

/// 语言
#[derive(Clone, Debug)]
pub enum Language {
    ZhCN,
    ZhHans,
    En,
    Other(String),
}
impl Language {
    #[must_use]
    pub fn from(name: &str) -> Self {
        let binding = name.split(',').collect::<Vec<&str>>()[0]
            .trim()
            .to_lowercase();
        let name = binding.as_str();
        match name {
            "zh-cn" => Self::ZhCN,
            "zh-hans" => Self::ZhHans,
            "en" => Self::En,
            _ => Self::Other(name.to_string()),
        }
    }
    #[must_use]
    pub fn str(&self) -> &str {
        match self {
            Language::ZhCN => "zh-CN",
            Language::ZhHans => "zh-Hans",
            Language::En => "en",
            Language::Other(e) => e.as_str(),
        }
    }
}

/// 压缩方式
#[derive(Clone, Debug)]
pub enum Encoding {
    Gzip,
    Deflate,
    Br,
    Bzip2,
    None,
}
impl Encoding {
    #[must_use]
    pub fn from(s: &str) -> Encoding {
        match s.to_lowercase().as_str() {
            x if x.contains("gzip") => Encoding::Gzip,
            x if x.contains("deflate") => Encoding::Deflate,
            x if x.contains("br") => Encoding::Br,
            x if x.contains("bzip2") => Encoding::Bzip2,
            _ => Encoding::None,
        }
    }
    #[must_use]
    pub fn str(&self) -> &str {
        match self {
            Encoding::Gzip => "gzip",
            Encoding::Deflate => "deflate",
            Encoding::Br => "br",
            Encoding::Bzip2 => "bzip2",
            Encoding::None => "",
        }
    }
    /// 压缩
    pub fn compress(&mut self, data: &[u8]) -> Result<Vec<u8>, String> {
        match self {
            Encoding::Gzip => {
                let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
                match encoder.write_all(data) {
                    Ok(()) => {}
                    Err(e) => {
                        return Err(format!("Failed to compress file {}", e));
                    }
                };
                match encoder.finish() {
                    Ok(e) => Ok(e),
                    Err(e) => Err(format!("Failed to compress file {}", e)),
                }
            }
            _ => Ok(data.to_vec()),
        }
    }
    /// 解压
    pub fn decompress(&mut self, data: &[u8]) -> Result<Vec<u8>, String> {
        match self {
            Encoding::Gzip => {
                let mut d = GzDecoder::new(data);
                let mut s = String::new();
                match d.read_to_string(&mut s) {
                    Ok(_) => {}
                    Err(e) => {
                        return Err(format!("Failed to decompress file {}", e));
                    }
                };
                Ok(s.as_bytes().to_vec())
            }
            Encoding::Br => {
                let mut decompressed = Vec::new();
                let mut reader = brotli::Decompressor::new(data, 4096);
                reader
                    .read_to_end(&mut decompressed)
                    .map_err(|e| format!("brotli decompress error: {e}"))?;
                Ok(decompressed)
            }
            _ => Ok(data.to_vec()),
        }
    }
}

/// HTTP协议版本
#[derive(Clone, Debug)]
pub enum Protocol {
    HTTP1_0,
    HTTP1_1,
    HTTP2,
    HTTP3,
    Other(String),
}

impl Protocol {
    #[must_use]
    pub fn from(name: &str) -> Self {
        match name.to_lowercase().as_str() {
            "http/1.0" => Protocol::HTTP1_0,
            "http/1.1" => Protocol::HTTP1_1,
            "http/2.0" | "http/2" => Protocol::HTTP2,
            "http/3.0" | "http/3" => Protocol::HTTP3,
            _ => Protocol::Other(name.to_lowercase()),
        }
    }
    #[must_use]
    pub fn str(&self) -> &str {
        match self {
            Protocol::HTTP1_0 => "HTTP/1.0",
            Protocol::HTTP1_1 => "HTTP/1.1",
            Protocol::HTTP2 => "HTTP/2.0",
            Protocol::HTTP3 => "HTTP/3.0",
            Protocol::Other(protocol) => protocol.as_str(),
        }
    }
}
/// 响应状态
#[derive(Clone, Debug)]
pub struct Status {
    pub code: u16,
    reason: String,
}
impl Status {
    pub fn set_code(&mut self, code: u16) {
        self.code = code;
        self.reason = match code {
            100 => "Continue", // 服务器愿意接收请求实体(配合 Expect: 100-continue)。
            101 => "Switching Protocols", // 协议切换(如升级到 WebSocket)。
            102 => "Processing",
            103 => "Early Hints",        // 提前提示可预加载的资源。
            200 => "OK",                 // 请求成功(GET/PUT/PATCH 通用)
            201 => "Created",            // 已创建新资源(典型于 POST)
            202 => "Accepted",           // 已接受处理但未完成(异步任务)。
            204 => "No Content",         // 成功但无响应体(DELETE 常用)。
            206 => "Partial Content",    // 部分内容(Range 下载)。
            301 => "Moved Permanently",  // 永久重定向
            302 => "Found",              // 临时重定向(历史上易与 303/307混用)。
            303 => "See Other",          // 告诉客户端去 GET 另一个 URI(表单提交后跳详情页)。
            304 => "Not Modified",       // 资源未变更(配合缓存 ETag/Last-Modified)。
            307 => "Temporary Redirect", // 临时,不改变方法(POST 仍是 POST)
            308 => "Permanent Redirect", // 永久,不改变方法。

            400 => "Bad Request", // 请求报文有误/语法错误/JSON 无法解析/缺少必需字段或头。
            401 => "Unauthorized", // 未认证或凭证无效(要带 WWW-Authenticate)。
            403 => "Forbidden",
            404 => "Not Found", //服务器无法根据客户端的请求找到资源(网页)。通过此代码,网站设计人员可设置"您所请求的资源无法找到"的个性页面
            405 => "Method Not Allowed", // 方法不被允许(应返回 Allow 头)。
            411 => "Length Required", // 缺少 Content-Length。
            413 => "Payload Too Large", // 请求体过大。
            414 => "URI Too Long", // URI 太长。
            416 => "Range Not Satisfiable",
            429 => "Too Many Requests",               // 限流
            431 => "Request Header Fields Too Large", // 请求头过大。

            500 => "Internal Server Error", //服务器内部错误,无法完成请求
            501 => "Not Implemented",       //服务器不支持请求的功能,无法完成请求
            502 => "Bad Gateway", //作为网关或者代理工作的服务器尝试执行请求时,从远程服务器接收到了一个无效的响应
            503 => "Service Unavailable", //服务不可用/维护中(可带 Retry-After)。
            504 => "Gateway Time-out", //网关超时(上游响应超时)。
            505 => "HTTP Version Not Supported", //服务器不支持请求的HTTP协议的版本,无法完成处理
            _ => "",
        }
        .to_string();
    }
    #[must_use]
    pub fn from(code: u16, reason: &str) -> Self {
        Status {
            code,
            reason: reason.to_string(),
        }
    }
}
impl Default for Status {
    fn default() -> Self {
        Self {
            code: 200,
            reason: "OK".to_string(),
        }
    }
}

#[derive(Debug)]
pub enum TransferEncoding {
    Chunked,
    Other(String),
}
impl TransferEncoding {
    pub fn from(name: &str) -> TransferEncoding {
        match name.to_lowercase().as_str() {
            "chunked" => TransferEncoding::Chunked,
            _ => TransferEncoding::Other(name.to_string()),
        }
    }
}

pub fn split_boundary(mut data: Vec<u8>, boundary: &str) -> Result<Vec<Vec<u8>>, String> {
    let boundary = format!("--{boundary}");
    let boundary_bytes = boundary.as_bytes();
    let mut list = vec![];
    loop {
        if let Some(n) = data
            .windows(boundary_bytes.len())
            .position(|x| x == boundary_bytes)
        {
            // 修复:正确计算 drain 范围,移除从开始到 boundary 结束的部分
            let drain_end = n + boundary_bytes.len();
            if drain_end > data.len() {
                return Err("格式错误: boundary 超出数据范围".to_string());
            }
            data.drain(..drain_end);
            if data.is_empty() || data.starts_with(b"--\r\n") || data.starts_with(b"--") {
                break;
            }
            // 跳过 boundary 后的 CRLF
            if data.starts_with(b"\r\n") {
                data.drain(..2);
            }
        } else {
            return Err("格式错误: 未找到 boundary".to_string());
        }
        if let Some(n) = data
            .windows(boundary_bytes.len())
            .position(|x| x == boundary_bytes)
        {
            if n > 0 {
                // 移除末尾的 CRLF
                let content_end = if n >= 2 && data[n - 2..n] == *b"\r\n" {
                    n - 2
                } else {
                    n
                };
                list.push(data[..content_end].to_vec());
            }
            data.drain(..n);
        } else {
            return Err("格式错误: 未找到结束 boundary".to_string());
        }
    }
    Ok(list)
}