br-reqwest 0.0.21

This is an http
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
use json::{object, JsonValue};
use native_tls::{TlsConnector, TlsStream};
use rand::distr::Alphanumeric;
use rand::Rng;
use std::io::{Error, ErrorKind, Read, Write};
use std::net::TcpStream;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use std::{fs, io};
use url::Url;

#[derive(Debug, Clone)]
pub struct Client {
    debug: bool,
    url: Url,
    method: Method,
    pub header: JsonValue,
    version: Version,
    params: Vec<u8>,
    retry: usize,
    range_size: usize,
}
impl Default for Client {
    fn default() -> Self {
        Self::new()
    }
}

impl Client {
    pub fn new() -> Self {
        Self {
            debug: false,
            method: Method::None,
            url: Url::parse("http://127.0.0.1").unwrap(),
            header: object! {},
            version: Version::Http11,
            params: vec![],
            retry: 0,
            range_size: 0,
        }
    }
    pub fn debug(&mut self) -> &mut Self {
        self.debug = true;
        self
    }
    pub fn version(&mut self) -> String {
        self.version.as_str().to_string()
    }
    pub fn url(&mut self, url: &str) -> &mut Self {
        self.url = Url::parse(url).unwrap();
        self
    }
    pub fn method(&mut self, method: &str) -> &mut Self {
        self.method = Method::from_str(method);
        self
    }
    pub fn head(&mut self, url: &str) -> &mut Self {
        self.method = Method::Head;
        self.url = Url::parse(url).unwrap();
        self
    }
    pub fn get(&mut self, url: &str) -> &mut Self {
        self.method = Method::Get;
        self.url = Url::parse(url).unwrap();
        self
    }

    pub fn post(&mut self, url: &str) -> &mut Self {
        self.method = Method::Post;
        self.url = Url::parse(url).unwrap();
        self
    }

    pub fn put(&mut self, url: &str) -> &mut Self {
        self.method = Method::Put;
        self.url = Url::parse(url).unwrap();
        self
    }
    pub fn delete(&mut self, url: &str) -> &mut Self {
        self.method = Method::Delete;
        self.url = Url::parse(url).unwrap();
        self
    }
    pub fn patch(&mut self, url: &str) -> &mut Self {
        self.method = Method::Patch;
        self.url = Url::parse(url).unwrap();
        self
    }
    pub fn options(&mut self, url: &str) -> &mut Self {
        self.method = Method::Options;
        self.url = Url::parse(url).unwrap();
        self
    }
    /// 重试
    pub fn retry(&mut self, count: usize) -> &mut Self {
        self.retry = count;
        self
    }
    /// 分片
    pub fn range(&mut self, range_size: usize) -> &mut Self {
        self.range_size = range_size;
        self.make_range_header(Some(0), Some(range_size - 1));
        self
    }
    fn make_range_header(&mut self, start: Option<usize>, end: Option<usize>) {
        let res = match (start, end) {
            (Some(s), Some(e)) => Some(format!("bytes={}-{}", s, e)),
            (Some(s), None) => Some(format!("bytes={}-", s)),
            (None, Some(n)) => Some(format!("bytes=-{}", n)),
            (None, None) => None,
        };
        if let Some(e)=res {
            self.header("Range", e.as_str());
            self.header("Accept-Encoding", "identity");
            self.header("connection", "keep-alive");
        }
    }

    pub fn query(&mut self, data: JsonValue) -> &mut Self {
        let mut query = vec![];
        for (key, value) in data.entries() {
            query.push(format!("{}={}", key, value));
        }
        for (key, value) in self.url.query_pairs() {
            query.push(format!("{}={}", key, value));
        }
        self.url.set_query(Some(&query.join("&")));
        self
    }
    pub fn raw_json(&mut self, data: JsonValue) -> &mut Self {
        let _ = self.header.insert("Content-Type", "application/json");
        self.params = data.to_string().into_bytes();
        let _ = self.header.insert("Content-Length", self.params.len());
        self
    }
    pub fn body(&mut self, data: Vec<u8>) -> &mut Self {
        self.params = data;
        let _ = self.header.insert("Content-Length", self.params.len());
        self
    }
    pub fn form_data(&mut self, data: JsonValue) -> &mut Self {
        let rand_str: String = rand::rng()
            .sample_iter(&Alphanumeric)
            .take(30) // 取 30 个随机字符
            .map(char::from)
            .collect();
        let boundary = format!("----RustBoundary{}", rand_str);
        let _ = self.header.insert(
            "Content-Type",
            format!("multipart/form-data; boundary={boundary}"),
        );
        let mut params = vec![];
        for (key, value) in data.entries() {
            let res = PathBuf::from(value.to_string().as_str());
            if res.is_file() {
                let filename = res.file_name().unwrap().to_string_lossy();
                let value_b = fs::read(value.to_string()).unwrap();
                params.extend(format!("--{boundary}\r\n").as_bytes());
                params.extend(
                    format!(
                        r#"Content-Disposition: form-data; name="{key}"; filename="{filename}""#
                    )
                    .as_bytes(),
                );
                params.extend("\r\nContent-Type: application/octet-stream\r\n\r\n".as_bytes());
                params.extend(value_b);
                params.extend("\r\n".as_bytes());
            } else {
                params.extend(format!("--{boundary}\r\n").as_bytes());
                params
                    .extend(format!(r#"Content-Disposition: form-data; name="{key}""#).as_bytes());
                params.extend(b"Content-Type: text/plain; charset=utf-8");
                params.extend(format!("\r\n\r\n{value}\r\n").as_bytes());
            }
        }
        params.extend(format!("--{boundary}--\r\n").bytes());
        self.params = params.to_vec();
        let _ = self.header.insert("Content-Length", self.params.len());
        self
    }
    pub fn form_urlencoded(&mut self, data: JsonValue) -> &mut Self {
        let _ = self
            .header
            .insert("Content-Type", "application/x-www-form-urlencoded");
        let mut params = vec![];
        for (key, value) in data.entries() {
            params.push(format!("{}={}", key, value));
        }
        let params = params.join("&");
        self.params = params.as_bytes().to_vec();
        let _ = self.header.insert("Content-Length", self.params.len());
        self
    }
    pub fn header(&mut self, key: &str, value: &str) -> &mut Self {
        self.header.insert(key, value).expect("TODO: panic message");
        self
    }
    fn stream(&mut self) -> Result<HttpStream, Box<dyn std::error::Error>> {
        let port = self.url.port().unwrap_or_else(|| {
            if self.url.scheme() == "https" {
                443
            } else {
                80
            }
        });
        let host = self.url.host().unwrap().to_string();
        let mut stream = if port == 443 {
            let tcp = TcpStream::connect((host.clone(), port))?;
            let connector = TlsConnector::new()?;
            let stream = connector.connect(&host, tcp)?;
            HttpStream::Https(Arc::new(Mutex::new(stream)))
        } else {
            let tcp = TcpStream::connect((host.clone(), port))?;
            HttpStream::Http(Arc::new(Mutex::new(tcp)))
        };
        stream.set_read_timeout(Duration::from_secs(30))?;
        stream.set_write_timeout(Duration::from_secs(30))?;
        stream.set_nonblocking(false)?;
        stream.set_nodelay(true)?;
        Ok(stream)
    }
    fn request_txt(&mut self) -> io::Result<Vec<u8>> {
        let port = self.url.port().unwrap_or_else(|| {
            if self.url.scheme() == "https" {
                443
            } else {
                80
            }
        });
        let host = self.url.host().unwrap().to_string();
        let uri = if self.url.query().is_some() {
            format!("{}?{}", self.url.path(), self.url.query().unwrap())
        } else {
            self.url.path().to_string()
        };
        let mut header = vec![];
        header.push(format!(
            "{} {} {}",
            self.method.as_str(),
            uri,
            self.version.as_str()
        ));
        for (k, v) in self.header.entries() {
            header.push(format!("{k}: {v}"));
        }

        if !self.header.has_key("host") {
            let host_header = if (self.url.scheme() == "https" && port != 443)
                || (self.url.scheme() == "http" && port != 80)
            {
                format!("{}:{}", host, port)
            } else {
                host.clone()
            };
            header.push(format!("Host: {host_header}"));
        }
        header.push("\r\n".to_string());
        let request = header.join("\r\n");
        if self.debug {
            println!("================请求内容==============\r\n{}", request);
        }
        Ok(request.as_bytes().to_vec())
    }

    pub fn send_relay(
        &mut self,
        mut client: impl Write,
    ) -> Result<Response, Box<dyn std::error::Error>> {
        let mut retry = 0;
        let mut index = 0;
        let mut stream = self.stream()?;
        loop {
            stream.write_all(self.request_txt()?.as_slice())?;
            stream.flush()?;
            return match Response::new(stream.clone(), self.clone()) {
                Ok(mut e) => {
                    match e.code {
                        206 => {
                            if index == 0 {
                                let mut res = Response::new_protocol(
                                    Version::format(e.version.as_str()),
                                    200,
                                    "200 OK",
                                    e.header.clone(),
                                );
                                res.header["content-type"] = e.content_type.clone().into();
                                res.header["content-length"] = e.ranges_len.into();
                                res.header["connection"] = "keep-alive".into();
                                res.header["keep-alive"] = "timeout=120, max=1000".into();
                                res.header["accept-ranges"] = "bytes".into();
                                res.header["accept-encoding"] = "identity".into();
                                res.header.remove("content-range");
                                let res = res.generate_response_protocol();
                                client.write_all(res.as_slice())?;
                                index += 1;
                            }
                            match client.write_all(&e.body()) {
                                Ok(()) => {
                                    println!("发送成功: {}", e.body().len());
                                }
                                Err(err) => {
                                    println!("发送失败: {} {}", e.body().len(), err);
                                    return Err(Box::new(err));
                                }
                            };
                            if e.ranges_end + 1 < e.ranges_len {
                                let next_start = e.ranges_end + 1;
                                let mut next_end =
                                    next_start.saturating_add(self.range_size.saturating_sub(1));
                                if next_end >= e.ranges_len {
                                    next_end = e.ranges_len - 1;
                                }
                                self.make_range_header(Some(next_start), Some(next_end));
                                continue;
                            }
                            e.status = "OK".into();
                            e.code = 200;
                            Ok(e)
                        }
                        _ => Ok(e),
                    }
                }
                Err(e) => {
                    if self.retry > retry {
                        retry += 1;
                        println!("响应解析错误重试1: {}", e);
                        continue;
                    }
                    println!("响应解析错误: {}", e);
                    Err(Box::from(e.to_string()))
                }
            };
        }
    }
    pub fn send(&mut self) -> Result<Response, Box<dyn std::error::Error>> {
        let mut retry = 0;
        self.request_txt()?;
        let mut stream = self.stream()?;
        loop {
            let mut request = self.request_txt()?;
            if !self.params.is_empty() {
                request.extend(self.params.clone());
            }
            stream.write_all(request.as_slice())?;
            return match Response::new(stream.clone(), self.clone()) {
                Ok(mut e) => {
                    //match e.code {
                    //    206 => {
                    //        e.code=200;
                    //        e.status="OK".to_string();
                    //    }
                    //    _=>{}
                    //}
                    Ok(e)
                },
                Err(e) => {
                    if self.retry > retry {
                        retry += 1;
                        println!("响应解析错误重试2: {}", e);
                        continue;
                    }
                    println!("响应解析错误: {}", e);
                    Err(Box::from(e.to_string()))
                }
            };
        }
    }
}
#[derive(Debug, Clone)]
enum Method {
    Head,
    Get,
    Post,
    Put,
    Patch,
    Delete,
    Options,
    None,
}

impl Method {
    fn as_str(&self) -> &'static str {
        match self {
            Method::Head => "HEAD",
            Method::Get => "GET",
            Method::Post => "POST",
            Method::Put => "PUT",
            Method::Patch => "PATCH",
            Method::Delete => "DELETE",
            Method::Options => "OPTIONS",
            Method::None => "",
        }
    }
    fn from_str(method: &str) -> Method {
        match method.to_uppercase().as_str() {
            "HEAD" => Method::Head,
            "GET" => Method::Get,
            "POST" => Method::Post,
            "PUT" => Method::Put,
            "PATCH" => Method::Patch,
            "DELETE" => Method::Delete,
            "OPTIONS" => Method::Options,
            "NONE" => Method::None,
            _ => Method::None,
        }
    }
}

#[derive(Debug, Clone)]
pub enum HttpStream {
    Http(Arc<Mutex<TcpStream>>),
    Https(Arc<Mutex<TlsStream<TcpStream>>>),
    None,
}

impl HttpStream {
    pub fn set_nonblocking(&mut self, nonblocking: bool) -> Result<(), Error> {
        match self {
            HttpStream::Http(e) => e.lock().unwrap().set_nonblocking(nonblocking),
            HttpStream::Https(e) => e.lock().unwrap().get_mut().set_nonblocking(nonblocking),
            HttpStream::None => Err(Error::new(ErrorKind::TimedOut, "未知")),
        }
    }
    pub fn set_nodelay(&mut self, nodelay: bool) -> Result<(), Error> {
        match self {
            HttpStream::Http(e) => e.lock().unwrap().set_nodelay(nodelay),
            HttpStream::Https(e) => e.lock().unwrap().get_mut().set_nodelay(nodelay),
            HttpStream::None => Err(Error::new(ErrorKind::TimedOut, "未知")),
        }
    }

    pub fn write_all(&mut self, buf: &[u8]) -> Result<(), Error> {
        match self {
            HttpStream::Http(e) => e.lock().unwrap().write_all(buf),
            HttpStream::Https(e) => e.lock().unwrap().write_all(buf),
            HttpStream::None => Err(Error::new(ErrorKind::TimedOut, "未知")),
        }
    }
    pub fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        match self {
            HttpStream::Http(e) => e.lock().unwrap().read(buf),
            HttpStream::Https(e) => e.lock().unwrap().read(buf),
            HttpStream::None => Err(Error::new(ErrorKind::TimedOut, "未知")),
        }
    }
    pub fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        match self {
            HttpStream::Http(e) => e.lock().unwrap().write(buf),
            HttpStream::Https(e) => e.lock().unwrap().write(buf),
            HttpStream::None => Err(Error::new(ErrorKind::TimedOut, "未知")),
        }
    }
    pub fn flush(&mut self) -> io::Result<()> {
        match self {
            HttpStream::Http(e) => e.lock().unwrap().flush(),
            HttpStream::Https(e) => e.lock().unwrap().flush(),
            HttpStream::None => Err(Error::new(ErrorKind::TimedOut, "未知")),
        }
    }
    pub fn set_read_timeout(&mut self, timeout: Duration) -> io::Result<()> {
        match self {
            HttpStream::Http(e) => e.lock().unwrap().set_read_timeout(Some(timeout)),
            HttpStream::Https(e) => e.lock().unwrap().get_mut().set_read_timeout(Some(timeout)),
            HttpStream::None => Err(Error::new(ErrorKind::TimedOut, "未知")),
        }
    }
    pub fn set_write_timeout(&mut self, timeout: Duration) -> io::Result<()> {
        match self {
            HttpStream::Http(e) => e.lock().unwrap().set_write_timeout(Some(timeout)),
            HttpStream::Https(e) => e.lock().unwrap().get_mut().set_write_timeout(Some(timeout)),
            HttpStream::None => Err(Error::new(ErrorKind::TimedOut, "未知")),
        }
    }
}

#[derive(Debug)]
pub struct Response {
    /// 协议版本号
    version: String,
    header: JsonValue,
    body: Vec<u8>,
    stream: HttpStream,
    header_data: Vec<u8>,
    pub code: u16,
    pub status: String,
    pub content_type: String,
    pub ranges_len: usize,
    pub ranges_end: usize,
}
impl Response {
    pub fn new(stream: HttpStream, request: Client) -> Result<Response, Error> {
        let mut response = Response {
            version: "".to_string(),
            body: vec![],
            stream,
            header_data: vec![],
            header: object! {},
            code: 0,
            status: "".to_string(),
            content_type: "".to_string(),
            ranges_end: 0,
            ranges_len: 0,
        };
        loop {
            let mut buf = [0; 1024];
            match response.stream.read(&mut buf) {
                Ok(0) => {
                    if response.header_data.is_empty() {
                        return Err(Error::other("无请求头数据"));
                    }
                    break;
                }
                Ok(n) => {
                    response.header_data.extend(&buf[..n]);
                    if let Some(pos) = response
                        .header_data
                        .windows(4)
                        .position(|w| w == [13, 10, 13, 10])
                    {
                        response.body = response.header_data[pos + 4..].to_vec();
                        response.header_data = response.header_data[..pos].to_vec();
                        response.handle_header()?;
                        break;
                    }
                }
                Err(e) => return Err(e),
            }
        }
        if request.debug {
            println!(
                "================响应内容==============\r\n{}\r\n",
                String::from_utf8_lossy(&response.header_data)
            );
        }
        if let Method::Head = request.method {
            return Ok(response);
        }

        if let Ok(e) = response.get_header("content-length") {
            let len = e.parse::<usize>().unwrap();
            if len > 0 {
                if response.body.len() == len {
                    return Ok(response);
                }
                loop {
                    let mut buf = [0; 1024 * 1024];
                    match response.stream.read(&mut buf) {
                        Ok(0) => {
                            if len > response.body.len() {
                                continue;
                            };
                            if response.body.len() == len {
                                return Ok(response);
                            }
                        }
                        Ok(n) => {
                            response.body.extend(&buf[..n]);
                            if response.body.len() == len {
                                break;
                            }
                        }
                        Err(e) => return Err(e),
                    }
                }
            }
        }
        Ok(response)
    }
    pub fn new_protocol(version: Version, code: u16, status: &str, header: JsonValue) -> Response {
        Self {
            version: version.as_str().to_string(),
            code,
            status: status.to_string(),
            content_type: "".to_string(),
            ranges_len: 0,
            header,
            body: vec![],
            stream: HttpStream::None,
            header_data: vec![],
            ranges_end: 0,
        }
    }
    pub fn generate_response_protocol(&self) -> Vec<u8> {
        let mut res = vec![];
        res.push(format!("{} {}", self.version, self.status));

        for (key, value) in self.header.entries() {
            res.push(format!("{key}: {value}"));
        }
        res.push("\r\n".to_string());
        let res = res.join("\r\n").as_bytes().to_vec();
        res
    }
    pub fn new_header(stream: HttpStream) -> Result<Response, Error> {
        let mut response = Response {
            version: "".to_string(),
            body: vec![],
            stream,
            header_data: vec![],
            header: object! {},
            code: 0,
            status: "".to_string(),
            content_type: "".to_string(),
            ranges_end: 0,
            ranges_len: 0,
        };
        let mut buf = [0; 1024];
        loop {
            match response.stream.read(&mut buf) {
                Ok(0) => {
                    if response.header_data.is_empty() {
                        return Err(Error::other("无请求头数据"));
                    }
                    break;
                }
                Ok(n) => {
                    response.header_data.extend(&buf[..n]);
                    if let Some(pos) = response
                        .header_data
                        .windows(4)
                        .position(|w| w == [13, 10, 13, 10])
                    {
                        response.body = response.header_data[pos + 4..].to_vec();
                        response.header_data = response.header_data[..pos].to_vec();
                        response.handle_header()?;
                        break;
                    }
                }
                Err(e) => return Err(e),
            }
        }
        Ok(response)
    }
    pub fn handle_header(&mut self) -> Result<(), Error> {
        let res = match std::str::from_utf8(self.header_data.as_slice()) {
            Ok(e) => e,
            Err(e) => {
                return Err(Error::other(e.to_string()));
            }
        };

        let request_line = res.lines().next().unwrap();

        let mut parts = request_line.split_whitespace();
        self.version = parts.next().ok_or("缺少版本").unwrap_or("").to_string();
        self.code = parts
            .next()
            .ok_or("缺少状态码")
            .unwrap_or("")
            .parse::<u16>()
            .unwrap();
        self.status = parts.clone().collect::<Vec<&str>>().join(" ").clone();

        for line in res.lines().skip(1) {
            match line.find(":") {
                None => {}
                Some(e) => {
                    let key = &line[..e];
                    let value = &line[e + 1..].trim();
                    self.header[key.to_lowercase().as_str()] = value.trim().into();
                }
            }
        }
        if self.get_header("content-type").is_ok() {
            let content = self.get_header("content-type").unwrap().to_string();
            match content.find(";") {
                None => {
                    self.content_type = content;
                }
                Some(e) => {
                    self.content_type = content[..e].to_string();
                }
            }
        }
        if self.get_header("content-range").is_ok() {
            let content = self.get_header("content-range").unwrap().to_string();
            match content.find("/") {
                None => {}
                Some(e) => {
                    self.ranges_len = content[e + 1..].parse::<usize>().unwrap();
                    let bytes = content[..e].to_string();
                    match bytes.find("-") {
                        None => {}
                        Some(e) => {
                            self.ranges_end = bytes[e + 1..].parse::<usize>().unwrap();
                        }
                    }
                }
            }
        }

        Ok(())
    }
    pub fn get_header(&self, key: &str) -> Result<String, String> {
        if self.header[key].is_null() {
            Err("请求头不存在".to_string())
        } else {
            Ok(self.header[key].to_string())
        }
    }

    pub fn version(&self) -> String {
        self.version.clone()
    }
    pub fn status(&self) -> String {
        format!("{} {}", self.code, self.status)
    }
    pub fn headers(&self) -> JsonValue {
        self.header.clone()
    }
    pub fn content_type(&self) -> String {
        self.content_type.clone()
    }
    pub fn json(&self) -> Result<JsonValue, Error> {
        match String::from_utf8(self.body.clone()) {
            Ok(e) => match json::parse(&e) {
                Ok(e) => Ok(e),
                Err(e) => Err(Error::other(e.to_string())),
            },
            Err(e) => Err(Error::other(e.to_string())),
        }
    }
    pub fn txt(&self) -> Result<String, Error> {
        match String::from_utf8(self.body.clone()) {
            Ok(e) => Ok(e),
            Err(e) => Err(Error::other(e.to_string())),
        }
    }
    pub fn body(&self) -> Vec<u8> {
        self.body.clone()
    }
}

#[derive(Debug, Clone)]
pub enum Version {
    #[allow(dead_code)]
    Http10,
    #[allow(dead_code)]
    Http11,
    #[allow(dead_code)]
    Http2,
    #[allow(dead_code)]
    Http3,
    #[allow(dead_code)]
    None,
}
impl Version {
    fn as_str(&self) -> &'static str {
        match self {
            Version::Http10 => "HTTP/1.0",
            Version::Http11 => "HTTP/1.1",
            Version::Http2 => "HTTP/2",
            Version::Http3 => "HTTP/3",
            Version::None => "",
        }
    }
    pub fn format(version: &str) -> Version {
        match version {
            "HTTP/1.0" => Version::Http10,
            "HTTP/1.1" => Version::Http11,
            "HTTP/2" => Version::Http2,
            "HTTP/3" => Version::Http3,
            _ => Version::None,
        }
    }
}