br_http/
lib.rs

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
use json::{JsonValue, object};
use std::{fs, str};
use std::collections::HashMap;
use std::fmt::Debug;
use std::str::FromStr;
use log::debug;
use reqwest::{Method as OtherMethod};
use reqwest::blocking::multipart::{Form, Part};
use serde_json::Value;


#[derive(Debug)]
pub struct Http {
    pub url: String,
    method: Method,
    header: HashMap<String, String>,
    debug: bool,
    read_timeout: u64,
    write_timeout: u64,
    pub query: String,

    content_type: ContentType,
    param_form_data: Option<Form>,
    param_form_urlencoded: HashMap<String, String>,
    param_raw_json: Value,
    param_raw_text: String,
    param_raw_stream: Vec<u8>,
    status: u16,
    response_content_type: ContentType,
    response_header: HashMap<String, String>,

}

impl Default for Http {
    fn default() -> Self {
        Self::new()
    }
}

impl Http {
    pub fn new() -> Http {
        Self {
            url: "".to_string(),
            method: Method::new(),
            header: Default::default(),
            debug: false,
            read_timeout: 5,
            write_timeout: 5,
            query: "".to_string(),
            content_type: ContentType::None,
            param_form_data: None,
            param_form_urlencoded: Default::default(),
            param_raw_json: Default::default(),
            param_raw_text: "".to_string(),
            param_raw_stream: vec![],
            status: 0,
            response_content_type: ContentType::None,
            response_header: Default::default(),
        }
    }
    pub fn set_read_timeout(&mut self, secs: u64) -> &mut Self {
        self.read_timeout = secs;
        self
    }
    pub fn set_write_timeout(&mut self, secs: u64) -> &mut Self {
        self.write_timeout = secs;
        self
    }
    /// 调试
    pub fn debug(&mut self, open: bool) -> &mut Self {
        self.debug = open;
        self
    }
    /// GET请求
    pub fn get(&mut self, url: &str) -> &mut Self {
        self.url = url.to_string();
        self.method = Method::GET;
        self
    }
    /// POST请求
    pub fn post(&mut self, url: &str) -> &mut Http {
        self.url = url.to_string();
        self.method = Method::POST;
        self
    }
    pub fn options(&mut self, url: &str) -> &mut Http {
        self.url = url.to_string();
        self.method = Method::OPTIONS;
        self
    }
    pub fn put(&mut self, url: &str) -> &mut Http {
        self.url = url.to_string();
        self.method = Method::PUT;
        self
    }
    pub fn patch(&mut self, url: &str) -> &mut Http {
        self.url = url.to_string();
        self.method = Method::PATCH;
        self
    }
    pub fn head(&mut self, url: &str) -> &mut Http {
        self.url = url.to_string();
        self.method = Method::HEAD;
        self
    }
    pub fn delete(&mut self, url: &str) -> &mut Http {
        self.url = url.to_string();
        self.method = Method::DELETE;
        self
    }
    pub fn header(&mut self, key: &str, value: &str) -> &mut Http {
        self.header.insert(key.to_string(), value.to_string());
        self
    }
    /// bearer 登陆头
    pub fn bearer_auth(&mut self, token: &str) -> &mut Http {
        self.header.insert("Authorization".to_string(), format!("Bearer {}", token));
        self
    }
    pub fn cookie(&mut self, key: &str, value: &str) -> &mut Http {
        self.header.insert("Cookie".to_string(), format!("{}={}", key, value));
        self
    }
    /// query 请求地址参数
    pub fn query(&mut self, mut data: JsonValue) -> &mut Self {
        self.content_type = ContentType::Plain;
        let mut t = vec![];
        for (key, value) in data.entries_mut() {
            t.push(format!("{}={}", key, value))
        };
        self.query = t.join("&");
        if !self.query.is_empty() && !self.url.contains("?") {
            self.url = format!("{}?{}", self.url, self.query);
        }
        self
    }
    /// form-data 数据类型
    pub fn form_data(&mut self, data: Vec<FormData>) -> &mut Self
    {
        self.content_type = ContentType::FormData;

        let mut form = Form::new();
        for item in data {
            match item {
                FormData::Text(key, value, mime) => {
                    let r = if !mime.is_empty() {
                        Part::text(value.to_string()).mime_str(mime.clone().as_str())
                    } else {
                        Ok(Part::text(value.to_string()))
                    };
                    form = form.part(key, r.unwrap());
                }
                FormData::File(key, path, mime) => {
                    let r = if !mime.is_empty() {
                        Part::bytes(fs::read(path).unwrap()).file_name(key.to_string()).mime_str(mime.clone().as_str())
                    } else {
                        Ok(Part::bytes(fs::read(path).unwrap()).file_name(key.to_string()))
                    };
                    form = form.part(key, r.unwrap());
                }
                FormData::None => {}
            }
        }
        self.param_form_data = Some(form);
        self
    }
    /// form-urlencoded 数据类型
    pub fn form_urlencoded(&mut self, data: JsonValue) -> &mut Self {
        self.content_type = ContentType::FormUrlencoded;
        let mut params = HashMap::new();
        for (key, value) in data.entries() {
            params.insert(key.to_string(), value.to_string());
        }
        self.param_form_urlencoded = params;
        self
    }
    /// json 数据类型
    pub fn raw_json(&mut self, data: JsonValue) -> &mut Self {
        self.content_type = ContentType::Json;
        if !data.is_empty() {
            self.param_raw_json = Value::from_str(&data.dump()).unwrap();
        }
        self
    }
    pub fn raw_javascript(&mut self, data: &str) -> &mut Self {
        self.header("Content-Type", ContentType::Javascript.str().as_str());
        self.content_type = ContentType::Javascript;
        self.param_raw_text = data.to_string();
        self
    }
    pub fn raw_xml(&mut self, data: &str) -> &mut Self {
        self.header("Content-Type", ContentType::Xml.str().as_str());
        self.content_type = ContentType::Xml;
        self.param_raw_text = data.to_string();
        self
    }
    pub fn raw_html(&mut self, data: &str) -> &mut Self {
        self.header("Content-Type", ContentType::Html.str().as_str());
        self.content_type = ContentType::Html;
        self.param_raw_text = data.to_string();
        self
    }
    pub fn raw_text(&mut self, data: &str) -> &mut Self {
        self.header("Content-Type", ContentType::Plain.str().as_str());
        self.content_type = ContentType::Plain;
        self.param_raw_text = data.to_string();
        self
    }
    pub fn raw_stream(&mut self, data: Vec<u8>) -> &mut Self {
        self.header("Content-Type", ContentType::Stream.str().as_str());
        self.content_type = ContentType::Stream;
        self.header("Content-Length", data.len().to_string().leak());
        self.param_raw_stream = data;
        self
    }
    pub fn raw_binary(&mut self, data: Vec<u8>, content_type: &str) -> &mut Self {
        self.header("Content-Type", content_type);
        self.content_type = ContentType::Stream;
        self.header("Content-Length", data.len().to_string().leak());
        self.param_raw_stream = data;
        self
    }

    /// 发送回执
    fn send(&mut self, mode: &str) -> Result<Vec<u8>, String> {
        let client = reqwest::blocking::Client::new();
        let mut request = match self.method {
            Method::GET => {
                client.get(self.url.as_str())
            }
            Method::POST => {
                client.post(self.url.as_str())
            }
            Method::OPTIONS => {
                client.request(OtherMethod::OPTIONS, self.url.as_str())
            }
            Method::PATCH => {
                client.patch(self.url.as_str())
            }
            Method::HEAD => {
                client.head(self.url.as_str())
            }
            Method::DELETE => {
                client.delete(self.url.as_str())
            }
            Method::PUT => {
                client.put(self.url.as_str())
            }
            Method::TRACE => {
                client.request(OtherMethod::TRACE, self.url.as_str())
            }
            Method::NONE => {
                client.request(OtherMethod::CONNECT, self.url.as_str())
            }
        };

        match self.content_type {
            ContentType::FormData => {
                request = request.multipart(self.param_form_data.take().unwrap());
            }
            ContentType::FormUrlencoded => {
                request = request.form(&self.param_form_urlencoded);
            }
            ContentType::Json => {
                request = request.json(&self.param_raw_json);
            }
            ContentType::Xml | ContentType::Plain | ContentType::Html | ContentType::Javascript => {
                let body = self.param_raw_text.as_mut_str();
                request = request.body(body.as_bytes().to_vec());
            }
            ContentType::Stream => {
                request = request.body(self.param_raw_stream.clone());
            }
            ContentType::None => {
                let body = self.param_raw_text.as_mut_str();
                request = request.body(body.as_bytes().to_vec());
            }
        }


        for (key, value) in self.header.iter() {
            request = request.header(key.clone(), value.clone());
        }

        if self.debug {
            debug!("发送数据: {:#?}",request);
        }
        match request.send() {
            Ok(e) => {
                if self.debug {
                    debug!("返回数据: {:#?}",e);
                }
                self.status = e.status().as_u16();
                self.response_header = HashMap::new();
                for (key, value) in e.headers().clone() {
                    if key.clone().is_some() {
                        self.response_header.insert(key.unwrap().to_string(), value.to_str().unwrap().trim_start_matches("\"").trim_end_matches("\"").to_string());
                    }
                }
                match self.response_header.get("content-type") {
                    Some(header) => {
                        let value = header.clone();
                        self.response_content_type = ContentType::from(&value);
                        match value {
                            s if s.contains("application/json") => {
                                let json = e.json::<Value>();
                                match json {
                                    Ok(e) => {
                                        Ok(e.to_string().as_bytes().to_vec())
                                    }
                                    Err(e) => Err(e.to_string())
                                }
                            }
                            _ => {
                                let text = e.text();
                                match text {
                                    Ok(e) => {
                                        Ok(e.as_bytes().to_vec())
                                    }
                                    Err(e) => Err(e.to_string())
                                }
                            }
                        }
                    }
                    None => {
                        match mode {
                            "json" => {
                                let r = e.json::<Value>();
                                match r {
                                    Ok(e) => Ok(e.to_string().as_bytes().to_vec()),
                                    Err(_e) => Ok("".to_string().as_bytes().to_vec())
                                }
                            }
                            "text" => {
                                let r = e.text();
                                match r {
                                    Ok(e) => Ok(e.as_bytes().to_vec()),
                                    Err(e) => Err(e.to_string())
                                }
                            }
                            "cookie" => {
                                let cookies = e.cookies().collect::<Vec<_>>();
                                let mut list = HashMap::new();
                                for cookie in cookies.iter() {
                                    list.insert(cookie.name().to_string(), cookie.value().to_string());
                                }
                                Ok(JsonValue::from(list).dump().as_bytes().to_vec())
                            }
                            "stream" => {
                                let r = e.bytes().unwrap().to_vec();
                                Ok(r)
                            }
                            "info" => {
                                let r = e.text();
                                match r {
                                    Ok(e) => Ok(e.as_bytes().to_vec()),
                                    Err(e) => Err(e.to_string())
                                }
                            }
                            &_ => {
                                Ok(vec![])
                            }
                        }
                    }
                }
            }
            Err(e) => {
                Err(e.to_string())
            }
        }
    }
    pub fn cookies(&mut self) -> Result<JsonValue, String> {
        match self.send("cookie") {
            Ok(e) => {
                let res = unsafe { String::from_utf8_unchecked(e) };
                Ok(json::parse(&res).unwrap_or(object! {}))
            }
            Err(e) => Err(e)
        }
    }
    /// 返回 text
    pub fn text(&mut self) -> Result<String, String> {
        match self.send("text") {
            Ok(e) => {
                let res = unsafe { String::from_utf8_unchecked(e) };
                Ok(res)
            }
            Err(e) => Err(e)
        }
    }
    /// 返回 JSON
    pub fn json(&mut self) -> Result<JsonValue, String> {
        match self.send("json") {
            Ok(e) => {
                let res = unsafe { String::from_utf8_unchecked(e) };
                Ok(json::parse(&res).unwrap_or(object! {}))
            }
            Err(e) => Err(e)
        }
    }
    /// 返回 info
    pub fn info(&mut self) -> Result<(u16, String, String, HashMap<String, String>), String> {
        match self.send("info") {
            Ok(e) => {
                let res = unsafe { String::from_utf8_unchecked(e) };
                Ok((self.status, self.response_content_type.str(), res, self.response_header.clone()))
            }
            Err(e) => Err(e)
        }
    }

    pub fn stream(&mut self) -> Result<Vec<u8>, String> {
        match self.send("stream") {
            Ok(e) => Ok(e),
            Err(e) => Err(e)
        }
    }
}

#[derive(Clone, Debug)]
pub enum Method {
    GET,
    POST,
    OPTIONS,
    PATCH,
    HEAD,
    DELETE,
    TRACE,
    PUT,
    NONE,
}

impl Method {
    fn new() -> Self {
        Method::GET
    }
    pub fn to_str(&self) -> String {
        match self {
            Method::GET => "GET",
            Method::POST => "POST",
            Method::OPTIONS => "OPTIONS",
            Method::PATCH => "PATCH",
            Method::HEAD => "HEAD",
            Method::DELETE => "DELETE",
            Method::TRACE => "TRACE",
            Method::PUT => "PUT",
            Method::NONE => "NONE"
        }.to_string()
    }
}
#[derive(Clone, Debug)]
pub enum Version {
    Http09,
    Http10,
    Http11,
    H2,
    H3,
    None,
}

impl Version {
    pub fn str(&mut self) -> String {
        match self {
            Version::Http09 => "HTTP/0.9",
            Version::Http10 => "HTTP/1.0",
            Version::Http11 => "HTTP/1.1",
            Version::H2 => "HTTP/2.0",
            Version::H3 => "HTTP/3.0",
            Version::None => ""
        }.to_string()
    }
    pub fn from(name: &str) -> Version {
        match name {
            "HTTP/0.9" => Self::Http09,
            "HTTP/1.0" => Self::Http10,
            "HTTP/1.1" => Self::Http11,
            "HTTP/2.0" => Self::H2,
            "HTTP/3.0" => Self::H3,
            _ => Self::None
        }
    }
    pub fn set_version(name: &str) -> Version {
        match name {
            "0.9" => Self::Http09,
            "1.0" => Self::Http10,
            "1.1" => Self::Http11,
            "2.0" => Self::H2,
            "3.0" => Self::H3,
            _ => Self::None
        }
    }
}


/// 请求
#[derive(Clone, Debug)]
pub enum Body {
    Json(JsonValue),
    Text(String),
    Xml(String),
    FormData(Vec<u8>),
    XWwwFormUrlencoded(String),
    None,
}

impl Default for Body {
    fn default() -> Self {
        Self::new()
    }
}

impl Body {
    pub fn new() -> Body {
        Self::None
    }
    pub fn bytes(&mut self) -> Vec<u8> {
        match self {
            Body::Json(e) => e.to_string().as_bytes().to_vec(),
            Body::Text(e) => e.clone().as_bytes().to_vec(),
            Body::Xml(e) => e.clone().as_bytes().to_vec(),
            Body::FormData(e) => e.to_vec().clone(),
            Body::XWwwFormUrlencoded(e) => e.clone().as_bytes().to_vec(),
            Body::None => "".as_bytes().to_vec()
        }
    }
}

#[derive(Clone, Debug)]
pub enum ContentType {
    FormData,
    FormUrlencoded,
    Json,
    Xml,
    Plain,
    Html,
    Stream,
    Javascript,
    None,
}
impl ContentType {
    pub fn str(&mut self) -> String {
        match self {
            ContentType::Plain => "text/plain",
            ContentType::Html => "text/html",
            ContentType::Stream => "application/octet-stream",
            ContentType::Javascript => "application/javascript",
            ContentType::FormData => "multipart/form-data",
            ContentType::Json => "application/json",
            ContentType::Xml => "application/xml",
            ContentType::None => "",
            ContentType::FormUrlencoded => "application/x-www-form-urlencoded"
        }.to_string()
    }
    pub fn from(name: &str) -> Self {
        match name {
            "application/xml" => ContentType::Xml,
            "text/plain" => ContentType::Plain,
            "text/html" => ContentType::Html,
            "application/octet-stream" => ContentType::Stream,
            "application/javascript" => ContentType::Javascript,
            "multipart/form-data" => ContentType::FormData,
            "application/json" => ContentType::Json,
            "application/x-www-form-urlencoded" => ContentType::FormUrlencoded,
            _ => ContentType::None
        }
    }
}
#[derive(Clone, Debug)]
pub enum FormData {
    /// KEY
    /// value
    /// 文本类型
    Text(String, JsonValue, String),
    /// 文件名
    /// 文件路径
    /// 文件类型
    File(String, String, String),
    None,
}