br-web-server 0.5.15

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
use crate::Status;
use crate::request::{Request};
use chrono::{DateTime, Duration as dur, Utc};
use json::{object, JsonValue};
use log::{error, info};
use std::path::{Path, PathBuf};
use std::{fs, io, thread};
use std::io::{Error};
use hpack::Encoder;
use crate::{ContentType, Encoding, Handler, HttpError, Method, Protocol, Upgrade};
use crate::Protocol::HTTP2;
use crate::websocket::Websocket;
const FLAG_END_STREAM: u8 = 0x01;
const FLAG_END_HEADERS: u8 = 0x04;
/// 响应
#[derive(Clone, Debug)]
pub struct Response {
    pub request: Request,
    pub status: Status,
    pub headers: JsonValue,
    pub cookies: JsonValue,
    /// 消息体
    pub body: Vec<u8>,
    /// HTTP2 使用
    pub stream_id: u32,
    /// ws 通信密钥
    pub key: String,
    /// ws 版本
    pub version: String,
    pub factory: fn(out: Websocket) -> Box<dyn Handler>,
    /// 允许来源
    pub allow_origins: Vec<&'static str>,
    /// 允许方法
    pub allow_methods: Vec<&'static str>,
    /// 允许请求头
    pub allow_headers: Vec<&'static str>,
    /// 消息体类型
    pub content_type: ContentType,
}
impl Response {
    pub fn new(request: &Request, factory: fn(out: Websocket) -> Box<dyn Handler>) -> Self {
        Self {
            request: request.clone(),
            status: Status::default(),
            headers: object! {},
            cookies: object! {},
            body: vec![],
            stream_id: 0,
            key: String::new(),
            version: String::new(),
            factory,
            allow_origins: vec![],
            allow_methods: vec![],
            allow_headers: vec![],
            content_type: ContentType::Other(String::new()),
        }
    }
    pub fn handle(mut self) -> io::Result<()> {
        match self.request.upgrade {
            Upgrade::Websocket => {
                self.handle_protocol_ws()?;
                return Ok(());
            }
            Upgrade::Http | Upgrade::Other(_) => {}
            Upgrade::H2c => {
                let _ = self.handle_protocol_h2c();
            }
            }

        match self.request.protocol {
            Protocol::HTTP1_0 => self.handle_protocol_http0()?,
            Protocol::HTTP1_1 => self.handle_protocol_http1()?,
            Protocol::HTTP2 => self.handle_protocol_http2()?,
            Protocol::HTTP3 | Protocol::Other(_) => {}
            }
        Ok(())
    }
    fn handle_protocol_http0(&mut self) -> io::Result<()> {
        let websocket = Websocket::http(self.request.clone(), self.clone());
        let mut factory = (self.factory)(websocket);
        match self.request.method {
            Method::OPTIONS => {
                factory.on_options(self);
                match self.on_options() {
                    Ok(()) => {
                        match self.status(200).send() {
                            Ok(()) => {}
                            Err(e) => return Err(Error::other(format!("1004: {} {} {}", self.request.uri.path, e.code, e.body))),
                        }
                    }
                    Err(e) => return {
                        self.status(e.code).txt(e.body.as_str()).send().unwrap();
                        Ok(())
                    }
                }
            }
            Method::GET => {
                if let Ok(e) = self.read_resource() {
                    if self.request.header.has_key("range") {
                        return match self.status(206).range(&e).send() {
                            Ok(()) => Ok(()),
                            Err(e) => Err(Error::other(format!("1003: {} {} {}", self.request.uri.path, e.code, e.body))),
                        };
                    }
                    return match self.status(200).file(&e).send() {
                        Ok(_) => Ok(()),
                        Err(e) => Err(Error::other(format!("1003: {} {} {}", self.request.uri.path, e.code, e.body))),
                    };
                }
                factory.on_request(self.request.clone(), self);
                factory.on_response(self);
                match self.send() {
                    Ok(()) => {}
                    Err(e) => return Err(Error::other(format!("1002: {} {} {}", self.request.uri.path, e.code, e.body))),
                }
            }
            _ => {
                factory.on_request(self.request.clone(), self);
                factory.on_response(self);
                match self.send() {
                    Ok(_) => {}
                    Err(e) => return Err(Error::other(format!("1001: {} {}", e.code, e.body))),
                }
            }
        }
        Ok(())
    }
    fn handle_protocol_http1(&mut self) -> io::Result<()> {
        self.handle_protocol_http0()
    }
    fn handle_protocol_http2(&mut self) -> io::Result<()> {
        let websocket = Websocket::http(self.request.clone(), self.clone());
        let mut factory = (self.factory)(websocket);

        match self.request.method {
            Method::OPTIONS => {
                factory.on_options(self);
                match self.send() {
                    Ok(_) => {}
                    Err(e) => return Err(Error::other(format!("2001: {} {}", e.code, e.body))),
                };
            }
            Method::GET => {
                if let Ok(e) = self.read_resource() {
                    return match self.status(200).file(&e).send() {
                        Ok(_) => Ok(()),
                        Err(e) => Err(Error::other(e.body)),
                    };
                }
                factory.on_request(self.request.clone(), self);
                factory.on_response(self);
                match self.send() {
                    Ok(()) => {}
                    Err(e) => return Err(Error::other(format!("2002: {} {}", e.code, e.body))),
                }
            }
            _ => {
                factory.on_request(self.request.clone(), self);
                factory.on_response(self);
                match self.send() {
                    Ok(_) => {}
                    Err(e) => return Err(Error::other(format!("2003: {} {}", e.code, e.body))),
                }
            }
        }
        Ok(())
    }
    fn handle_protocol_ws(&mut self) -> io::Result<()> {
        let mut websocket = Websocket::new(self.request.clone(), self.clone());
        let _ = websocket.handle();
        Ok(())
    }
    fn handle_protocol_h2c(&mut self) -> Result<(), HttpError> {
        self.header("Upgrade", "h2c");
        self.header("Connection", "Upgrade");
        match self.status(101).send() {
            Ok(()) => self.headers.clear(),
            Err(e) => return Err(e)
        };
        self.request.protocol=HTTP2;
        self.request.scheme.lock().unwrap().http2_send_server_settings()?;
        let mut data = vec![];
        self.request.scheme.lock().unwrap().read(&mut data)?;

        let t = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n";
        if let Some(pos) = data.windows(t.len()).position(|window| window == t) {
            let _ = data.drain(..pos).collect::<Vec<u8>>();
            data.drain(..t.len());
        } else {
            return Err(HttpError::new(400, "请求行错误"));
        }
        let (_payload, _frame_type, flags, _stream_id) =  self.request.scheme.lock().unwrap().http2_packet(&mut data)?;
        if flags & 0x01 == 0 {
            self.request.scheme.lock().unwrap().http2_settings_ack()?;
        }
        let (_payload, _frame_type, _flags, _stream_id) =  self.request.scheme.lock().unwrap().http2_packet(&mut data)?;
        let (payload, _frame_type, _flags, _stream_id) =  self.request.scheme.lock().unwrap().http2_packet(&mut data)?;
        if payload.len() == 4 {
            let raw = u32::from_be_bytes(payload.clone().try_into().unwrap());
            let increment = raw & 0x7FFF_FFFF; // 屏蔽最高位保留位
            if self.request.config.debug {
                info!("WindowUpdate: increment = {} {:?}", increment,payload);
            }
        } else {
            return Err(HttpError::new(400, format!("Invalid WindowUpdate frame length: {}", payload.len()).as_str()));
        }
        Ok(())
    }
    /// 读取资源文件
    fn read_resource(&mut self) -> io::Result<PathBuf> {
        if self.request.uri.path != "/" {
            let file = self.request.config.root_path.join(self.request.config.public.clone()).join(self.request.uri.path.trim_start_matches('/'));
            if file.is_file() {
                return Ok(file);
            }
        }
        if self.request.uri.path == "/" {
            let file = self.request.config.root_path.join("webpage").join(self.request.config.webpage.clone()).join("index.html");
            if file.is_file() {
                return Ok(file);
            }
        } else {
            let file = self.request.config.root_path.join("webpage").join(self.request.config.webpage.clone()).join(self.request.uri.path.trim_start_matches('/'));
            if file.is_file() {
                return Ok(file);
            }
        }
        Err(Error::other("Not a file"))
    }
    pub fn status(&mut self, code: u16) -> &mut Self {
        self.status.set_code(code);
        self
    }
    /// 跳转
    pub fn location(&mut self, uri: &str) -> &mut Self {
        self.header("Location", uri);
        self
    }
    /// 设置 HOST
    pub fn set_host(&mut self, host: &str) -> &mut Self {
        self.header("Host", host);
        self
    }

    pub fn header(&mut self, key: &str, value: &str) -> &mut Self {
        self.headers[key] = value.into();
        self
    }
    pub fn cookie(&mut self, key: &str, value: &str) -> &mut Self {
        self.cookies[key] = value.into();
        self
    }
    fn get_date(&self, s: i64) -> String {
        let utc: DateTime<Utc> = Utc::now();
        let future = utc + dur::seconds(s); // 加 3600 秒 = 1 小时
        future.format("%a, %d %b %Y %H:%M:%S GMT").to_string()
    }
    /// HTML 返回
    pub fn html(&mut self, value: &str) -> &mut Self {
        if self.request.config.charset.is_empty() {
            self.header("Content-Type", format!("{};", Extension::form("html").as_str()).as_str());
        } else {
            self.header("Content-Type", format!("{}; charset={}", Extension::form("html").as_str(), self.request.config.charset).as_str());
        }
        self.content_type = ContentType::Html;
        self.body = value.as_bytes().to_vec();
        self
    }
    /// TXT 返回
    pub fn txt(&mut self, value: &str) -> &mut Self {
        if self.request.config.charset.is_empty() {
            self.header("Content-Type", Extension::form("txt").as_str().to_string().as_str());
        } else {
            self.header("Content-Type", format!("{}; charset={}", Extension::form("txt").as_str(), self.request.config.charset).as_str());
        }
        self.content_type = ContentType::Text;
        self.body = value.as_bytes().to_vec();
        self
    }
    /// JSON 返回
    pub fn json(&mut self, value: JsonValue) -> &mut Self {
        if self.request.config.charset.is_empty() {
            self.header("Content-Type", Extension::form("json").as_str().to_string().as_str());
        } else {
            self.header("Content-Type", format!("{}; charset={}", Extension::form("json").as_str(), self.request.config.charset).as_str());
        }
        self.content_type = ContentType::Json;
        self.body = value.to_string().into_bytes();
        self
    }
    /// 下载 返回
    ///
    /// # Panics
    ///
    /// This function will panic if:
    /// - `filename.extension()` returns `None`
    /// - The extension cannot be converted to a valid UTF-8 string
    /// - The filename cannot be converted to a valid UTF-8 string
    pub fn download(&mut self, filename: &Path) -> &mut Self {
        let Ok(file) = fs::read(filename) else {
            self.status(404);
            return self;
        };
        let extension = filename.extension().unwrap().to_str().unwrap().to_lowercase();

        if self.request.config.charset.is_empty() {
            self.header("Content-Type", Extension::form(extension.as_str()).as_str().to_string().as_str());
        } else {
            self.header("Content-Type", format!("{}; charset={}", Extension::form(extension.as_str()).as_str(), self.request.config.charset).as_str());
        }

        let encoded_file_name = br_crypto::encoding::urlencoding_encode(filename.file_name().unwrap().to_str().unwrap());
        self.header("Content-Disposition", format!(r"attachment; filename={encoded_file_name}").as_str());
        self.header("Cache-Control", "no-cache");
        self.header("ETag", br_crypto::md5::encrypt_hex(&file).as_str());
        self.body = file;
        self
    }
    /// 分片
    pub fn range(&mut self, filename: &Path) -> &mut Self {
        let Ok(file) = fs::read(filename) else {
            self.status(404);
            return self;
        };
        let range = self.request.header["range"].to_string();
        let range = range.trim_start_matches("bytes=");
        let range = range.split("-").collect::<Vec<&str>>();
        let range_start = range[0].parse::<usize>().unwrap();
        let range_end = range[1].parse::<usize>().unwrap();

        if file.len() < range_end {
            self.status(416);
            self.header("Content-Range", format!("bytes */{}", file.len()).as_str());
            return self;
        }

        let extension = filename.extension().unwrap().to_str().unwrap().to_lowercase();

        if self.request.config.charset.is_empty() {
            self.header("Content-Type", Extension::form(extension.as_str()).as_str().to_string().as_str());
        } else {
            self.header("Content-Type", format!("{}; charset={}", Extension::form(extension.as_str()).as_str(), self.request.config.charset).as_str());
        }

        self.header("Accept-Ranges", "bytes");
        self.header("content-length", (range_end - range_start + 1).to_string().as_str());
        self.header("Content-Range", format!("bytes {}-{}/{}", range_start, range_end, file.len()).as_str());
        self.body = file[range_start..=range_end].to_vec();
        self
    }
    /// Serves a file for inline display in the browser.
    ///
    /// # 文件返回
    ///
    /// This function will panic if the file extension cannot be converted to a string,
    /// or if the filename cannot be converted to a valid UTF-8 string.
    pub fn file(&mut self, filename: &Path) -> &mut Self {
        let Ok(file) = fs::read(filename) else {
            self.status(404);
            return self;
        };

        self.header("Access-Control-Expose-Headers", "Content-Disposition");
        let extension = match filename.extension() {
            None => String::new(),
            Some(e) => e.to_str().unwrap().to_lowercase(),
        };
        if self.request.config.charset.is_empty() {
            self.header("Content-Type", Extension::form(extension.as_str()).as_str().to_string().as_str());
        } else {
            self.header("Content-Type", format!("{}; charset={}", Extension::form(extension.as_str()).as_str(), self.request.config.charset).as_str());
        }

        self.header("Content-Disposition", format!(r#"inline; filename="{}""#, filename.file_name().unwrap().to_str().unwrap()).as_str());

        self.header("Accept-Ranges", "bytes");

        self.header("Cache-Control", format!("public, max-age={}", 81400).as_str());
        self.header("Expires", &self.clone().get_date(81400));
        self.body = file;
        self
    }
    /// Sends the response over the given scheme.
    ///
    /// # Errors
    ///
    /// Returns an error if writing the response over the scheme fails.
    pub fn send(&mut self) -> Result<(), HttpError> {
        match &self.request.protocol {
            Protocol::HTTP1_0 | Protocol::HTTP1_1 => Ok(self.send_http1()?),
            Protocol::HTTP2 => Ok(self.send_http2()?),
            Protocol::HTTP3 => {
                error!("Other1:{:?} {:?}", thread::current().id(),self.request);
                Err(HttpError::new(500, "暂未实现HTTP3"))
            }
            Protocol::Other(e) => {
                error!("Other:{:?} {:?}", thread::current().id(),self.request);
                Err(HttpError::new(500, format!("暂未实现Other: {} {} {:?}", e, self.request.uri.path, thread::current().id()).as_str()))
            }
        }
    }
    fn send_http1(&mut self) -> Result<(), HttpError> {
        let mut header = vec![];
        header.push(format!("{} {} {}", self.request.protocol.str(), self.status.code, self.status.reason));
        self.header("Date", &self.get_date(0));

        match self.request.method {
            Method::HEAD => {
                self.header("Content-Length", self.body.len().to_string().as_str());
                self.body = vec![];
            }
            Method::OPTIONS => {
                self.body = vec![];
            }
            _ => {
                match self.request.accept_encoding {
                    Encoding::Gzip => {
                        self.header("Content-Encoding", self.request.accept_encoding.clone().str());
                        if let Ok(e) = self.request.accept_encoding.compress(&self.body.clone()) { self.body = e };
                        self.header("Content-Length", self.body.len().to_string().as_str());
                    }
                    _ => { self.header("Content-Length", self.body.len().to_string().as_str()); }
                }
            }
        };

        for (key, value) in self.headers.entries() {
            header.push(format!("{key}: {value}"));
        }

        for (key, value) in self.cookies.entries() {
            header.push(format!("Set-Cookie: {key}={value}; Path=/; HttpOnly; SameSite=Lax"));
        }

        if self.request.config.debug {
            info!("\r\n=================响应信息 {:?}=================\r\n{}\r\n===========================================",thread::current().id(),header.join("\r\n"));
            match self.request.accept_encoding {
                Encoding::Gzip => {}
                _ => {
                    match self.content_type {
                        ContentType::Text | ContentType::Html | ContentType::Json | ContentType::FormUrlencoded => {
                            info!("\r\n=================响应体 {:?}=================\r\n{}\r\n===========================================",thread::current().id(),String::from_utf8_lossy(self.body.as_slice()));
                        }
                        _ => {}
                    };
                }
            }
        }
        let mut headers = format!("{}\r\n\r\n", header.join("\r\n")).into_bytes();
        headers.extend(self.body.clone());
        self.request.scheme.lock().unwrap().write_all(headers.as_slice())?;
        Ok(())
    }
    fn send_http2(&mut self) -> Result<(), HttpError> {

        let max_frame_size: usize = 16_384;
        self.stream_id += 1;
        // 先构建所有帧,避免持锁期间借用 self
        let header_frames = self.http2_header(self.stream_id, max_frame_size);
        let data_frames = self.http2_body(self.stream_id, true, max_frame_size);

        // 仅锁一次写端,顺序写出所有帧
        let mut writer = self.request.scheme.lock().unwrap();
        for f in header_frames.clone() { writer.write_all(&f)?; }
        for f in data_frames.clone() { writer.write_all(&f)?; }
        Ok(())
    }

    fn http2_header(&mut self, stream_id: u32, max_frame_size: usize) -> Vec<Vec<u8>> {
        let mut headers: Vec<(Vec<u8>, Vec<u8>)> = vec![
            (b":status".to_vec(), self.status.code.to_string().into_bytes()),
            (b"date".to_vec(), self.get_date(0).into_bytes()),
        ];

        match self.request.method {
            Method::HEAD => {
                self.header("content-length", self.body.len().to_string().as_str());
                self.body.clear(); // HEAD 响应不携带实体
            }
            Method::OPTIONS => {
                self.body.clear();
                self.header("content-length", "0");
            }
            _ => {
                self.header("content-length", self.body.len().to_string().as_str());
            }
        }

        headers.extend(
            self.headers.entries().map(|(k, v)| (k.to_string().to_lowercase().into_bytes(), v.to_string().into_bytes()))
        );
        headers.extend(
            self.cookies.entries().map(|(k, v)| (b"set-cookie".to_vec(), format!("{k}={v}; Path=/; HttpOnly; SameSite=Lax").into_bytes()))
        );

        if self.request.config.debug {
            let dbg = headers.iter().map(|(n, v)| {
                format!("{}: {}", String::from_utf8_lossy(n), String::from_utf8_lossy(v))
            }).collect::<Vec<_>>().join("\r\n");
            info!("\n=================响应信息 {:?}=================\n{}\n===========================================",
              std::thread::current().id(), dbg);
        }

        let mut encoder = Encoder::new();
        // 2) HPACK 编码
        let block = encoder.encode(headers.iter().map(|h| (&h.0[..], &h.1[..])));

        let end_stream = self.body.is_empty();
        let mut frames = Vec::new();
        let mut remaining = block.as_slice();
        let mut first = true;

        while !remaining.is_empty() {
            let take = remaining.len().min(max_frame_size);
            let (chunk, rest) = remaining.split_at(take);
            remaining = rest;

            let is_last = remaining.is_empty();
            let mut flags = 0u8;
            if is_last { flags |= FLAG_END_HEADERS; }
            if is_last && end_stream { flags |= FLAG_END_STREAM; }

            // 9字节帧头
            let mut f = Vec::with_capacity(9 + chunk.len());
            let len = chunk.len();
            f.push(((len >> 16) & 0xFF) as u8);
            f.push(((len >> 8) & 0xFF) as u8);
            f.push((len & 0xFF) as u8);
            f.push(if first { 0x01 } else { 0x09 }); // HEADERS / CONTINUATION
            f.push(flags);
            f.extend_from_slice(&(stream_id & 0x7FFF_FFFF).to_be_bytes());
            f.extend_from_slice(chunk);

            frames.push(f);
            first = false;
        }

        // 如果 block 为空(极少见),也要至少发一个空 HEADERS(END_HEADERS [+END_STREAM])
        if frames.is_empty() {
            let mut f = vec![0, 0, 0, 0x01, FLAG_END_HEADERS | if end_stream { FLAG_END_STREAM } else { 0 }, 0, 0, 0, 0];
            f[5..9].copy_from_slice(&(stream_id & 0x7FFF_FFFF).to_be_bytes());
            frames.push(f);
        }

        frames
    }
    fn http2_body(&mut self, stream_id: u32, end_stream: bool, max_frame_size: usize) -> Vec<Vec<u8>> {
        if self.body.is_empty() {
            return Vec::new();
        }
        let mut frames = Vec::new();
        let mut off = 0usize;
        let total = self.body.len();

        while off < total {
            let take = (total - off).min(max_frame_size);
            let chunk = &self.body[off..off + take];
            off += take;

            let last = off == total;
            frames.push(self.build_data_frame(stream_id, chunk, last && end_stream));
        }
        frames
    }
    fn build_data_frame(&self, stream_id: u32, payload: &[u8], end_stream: bool) -> Vec<u8> {
        let len = payload.len();
        let mut f = Vec::with_capacity(9 + len);
        f.push(((len >> 16) & 0xFF) as u8);
        f.push(((len >> 8) & 0xFF) as u8);
        f.push((len & 0xFF) as u8);
        f.push(0x00); // DATA
        f.push(if end_stream { FLAG_END_STREAM } else { 0 });
        f.extend_from_slice(&(stream_id & 0x7FFF_FFFF).to_be_bytes());
        if !payload.is_empty() { f.extend_from_slice(payload); }
        f
    }
    fn on_options(&mut self) -> Result<(), HttpError> {
        if self.allow_origins.is_empty() {
            self.header("Access-Control-Allow-Origin", "*");
        } else if self.request.header.has_key("origin") {
            if self.allow_origins.contains(&self.request.origin.as_str()) {
                self.header("Access-Control-Allow-Origin", self.request.origin.to_string().as_str());
            } else {
                return Err(HttpError::new(403, "Origin not allowed"));
            }
        } else {
            return Err(HttpError::new(403, "Origin not allowed"));
        }

        if self.allow_headers.is_empty() {
            if !self.request.header.has_key("access-control-request-headers") {
                return Err(HttpError::new(403, "headers not allowed"));
            }
            self.header("Access-Control-Allow-Headers", self.request.header["access-control-request-headers"].to_string().as_str());
        } else if !self.request.header.has_key("access-control-request-headers") {
            let headers = self.allow_headers.join(",");
            self.header("Access-Control-Allow-Headers", headers.to_string().as_str());
        } else {
            let headers = self.allow_headers.join(",");
            self.header("Access-Control-Allow-Headers", format!("{},{}", self.request.header["access-control-request-headers"], headers).as_str());
        }

        if self.allow_methods.is_empty() {
            if !self.request.header.has_key("access-control-request-method") {
                return Err(HttpError::new(403, "methods not allowed"));
            }
            self.header("Access-Control-Allow-Methods", self.request.header["access-control-request-method"].to_string().as_str());
        } else {
            let methods = self.allow_methods.join(",");
            self.header("Access-Control-Allow-Methods", methods.to_string().as_str());
        }
        self.header("Vary", "Origin, Access-Control-Request-Method, Access-Control-Request-Headers");
        Ok(())
    }
}


/// 文件类型
enum Extension {}
impl Extension {
    pub fn form(extension: &str) -> String {
        match extension.to_lowercase().as_str() {
            "html" => "text/html",
            "css" => "text/css",
            "js" => "application/javascript",
            "json" => "application/json",
            "png" => "image/png",

            "mp4" => "video/mp4",
            "jpg" | "jpeg" => "image/jpeg",
            "gif" => "image/gif",
            "txt" => "text/plain",
            "pdf" => "application/pdf",
            "svg" => "image/svg+xml",
            "woff" => "application/font-woff",
            "woff2" => "application/font-woff2",
            "xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            _ => "application/octet-stream",
        }.to_string()
    }
}