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
//! 请求封装
use std::collections::HashMap;
use std::fmt::Display;

use bytes::Bytes;

use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
use reqwest::Body;
use serde_json::value::Value;
use std::convert::From;
use std::str::FromStr;
use std::time::Duration;

use reqwest;

pub struct Request;
use serde;

#[derive(Debug, serde::Serialize, serde::Deserialize, PartialEq)]
pub struct InitiateMultipartUploadResult {
    #[serde(rename(deserialize = "Bucket"))]
    bucket: String,
    #[serde(rename(deserialize = "Key"))]
    key: String,
    #[serde(rename(deserialize = "UploadId"))]
    pub upload_id: String,
}

/// ```
/// use rust_qcos::request::{CompleteMultipartUpload, Part};
/// use quick_xml::se::to_string;
/// let objs = CompleteMultipartUpload{part:vec![Part{part_number: 1, etag: "abc".to_string()}, Part{part_number: 2, etag: "abc".to_string()}]};
/// let s = to_string(&objs).unwrap();
/// assert_eq!(s, r#"<CompleteMultipartUpload><Part><PartNumber>1</PartNumber><ETag>abc</ETag></Part><Part><PartNumber>2</PartNumber><ETag>abc</ETag></Part></CompleteMultipartUpload>"#)
/// ```
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct CompleteMultipartUpload {
    #[serde(rename(serialize = "Part"))]
    pub part: Vec<Part>,
}

#[derive(Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq, Clone)]
pub struct Part {
    #[serde(rename = "$unflatten=PartNumber")]
    pub part_number: u64,
    #[serde(rename = "$unflatten=ETag")]
    pub etag: String,
}

/// 错误码
#[derive(Debug, PartialEq)]
pub enum ErrNo {
    /// 操作成功
    SUCCESS = 0,
    /// 其他错误
    OTHER = 10000,
    /// http status code 相关错误
    STATUS = 10001,
    /// 解码相关错误
    DECODE = 10002,
    /// 连接相关错误
    CONNECT = 10003,
    /// 编码相关错误
    ENCODE = 20001,
    /// IO错误
    IO = 20002,
}

/// 请求方法
#[derive(Debug, Eq, PartialEq)]
pub enum Method {
    Get,
    Post,
    Delete,
    Put,
    Head,
}

/// # Examples
/// ```
/// use rust_qcos::request::ErrNo;
/// println!("{:#?}", ErrNo::OTHER);
/// ```
impl ToString for ErrNo {
    fn to_string(&self) -> String {
        format!("{:#?}", self)
    }
}

/// http请求返回类型,无论成功还是失败都返回该类型,根据`error_no`可区分是否成功
#[derive(Debug)]
pub struct Response {
    /// 错误码
    pub error_no: ErrNo,
    /// 错误信息
    pub error_message: String,
    /// 接口返回信息,当接口返回错误时也可能有值
    pub result: Bytes,
    /// 接口返回的headers, 有些接口需要拿到头部信息进行校验
    pub headers: HashMap<String, String>,
}

impl From<reqwest::Error> for Response {
    fn from(value: reqwest::Error) -> Self {
        let mut e = ErrNo::OTHER;
        if value.is_status() {
            e = ErrNo::STATUS;
        } else if value.is_connect() {
            e = ErrNo::CONNECT;
        } else if value.is_decode() {
            e = ErrNo::DECODE;
        }
        Response {
            error_no: e,
            error_message: value.to_string(),
            result: Bytes::from(""),
            headers: HashMap::new(),
        }
    }
}

impl Display for Response {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            r#"{{"error_no": "{}","error_message": "{}","result": "{}"}}"#,
            self.error_no.to_string(),
            self.error_message,
            String::from_utf8_lossy(&self.result[..])
        )
    }
}

impl Response {
    pub fn new(error_no: ErrNo, error_message: String, result: String) -> Self {
        Self {
            error_no,
            error_message,
            result: Bytes::from(result),
            headers: HashMap::new(),
        }
    }
    /// 生成一个空的成功的`Response`对象
    pub fn blank_success() -> Self {
        Self::new(ErrNo::SUCCESS, "".to_string(), "".to_string())
    }
}

type Data = Value;

/// 请求封装类
impl Request {
    /// 从传入的`headers`参数生成`reqwest::blocking::ClientBuilder`
    fn get_builder_with_headers(
        headers: Option<&HashMap<String, String>>,
    ) -> reqwest::ClientBuilder {
        let mut builder = reqwest::ClientBuilder::new();
        if let Some(headers) = headers {
            let mut header = HeaderMap::new();
            for (k, v) in headers {
                header.insert(
                    HeaderName::from_str(k).unwrap(),
                    HeaderValue::from_str(v).unwrap(),
                );
            }
            builder = builder.default_headers(header);
        }
        builder
    }
    /// send Head request
    /// # Examples
    /// ```
    /// use rust_qcos::request::Request;
    /// use std::collections::HashMap;
    /// async {
    /// let mut headers = HashMap::new();
    /// headers.insert("x-test-header".to_string(), "test-header".to_string());
    /// Request::head("https://www.baiduc.com", None, Some(&headers)).await;
    /// };
    /// ```
    pub async fn head(
        url: &str,
        query: Option<&HashMap<String, String>>,
        headers: Option<&HashMap<String, String>>,
    ) -> Result<Response, Response> {
        Request::do_req(
            Method::Head,
            url,
            query,
            headers,
            None,
            None,
            None as Option<Body>,
        )
        .await
    }
    /// send get request
    /// # Examples
    /// ```
    /// use rust_qcos::request::Request;
    /// use std::collections::HashMap;
    /// async {
    /// let mut headers = HashMap::new();
    /// headers.insert("x-test-header".to_string(), "test-header".to_string());
    /// Request::get("https://www.baiduc.com", None, Some(&headers)).await;
    /// };
    /// ```
    pub async fn get(
        url: &str,
        query: Option<&HashMap<String, String>>,
        headers: Option<&HashMap<String, String>>,
    ) -> Result<Response, Response> {
        Request::do_req(
            Method::Get,
            url,
            query,
            headers,
            None,
            None,
            None as Option<Body>,
        )
        .await
    }
    /// send post request
    /// # Examples
    /// ```
    /// use reqwest::Body;
    /// use rust_qcos::request::Request;
    /// use std::collections::HashMap;
    /// use serde_json::json;
    /// async {
    /// let mut form = HashMap::new();
    /// form.insert("hello", json!(1i16));
    /// form.insert("hello1", json!("world"));
    /// let mut json = HashMap::new();
    /// json.insert("hello", json!(1i64));
    /// json.insert("hello_json", json!("world"));
    /// json.insert("data", json!(vec![1u8, 2u8, 3u8] as Vec<u8>));
    /// let resp = Request::post(
    ///     "https://www.baidu.com",
    ///     None,
    ///     None,
    ///     Some(&form),
    ///     Some(&json),
    ///     None as Option<Body>,
    /// ).await;
    /// };
    /// ```
    pub async fn post<T: Into<Body>>(
        url: &str,
        query: Option<&HashMap<String, String>>,
        headers: Option<&HashMap<String, String>>,
        form: Option<&HashMap<&str, Data>>,
        json: Option<&HashMap<&str, Data>>,
        body_data: Option<T>,
    ) -> Result<Response, Response> {
        Request::do_req(Method::Post, url, query, headers, form, json, body_data).await
    }

    /// send put request
    pub async fn put<T: Into<Body>>(
        url: &str,
        query: Option<&HashMap<String, String>>,
        headers: Option<&HashMap<String, String>>,
        form: Option<&HashMap<&str, Data>>,
        json: Option<&HashMap<&str, Data>>,
        body_data: Option<T>,
    ) -> Result<Response, Response> {
        Request::do_req(Method::Put, url, query, headers, form, json, body_data).await
    }

    /// send delete request
    pub async fn delete(
        url: &str,
        query: Option<&HashMap<String, String>>,
        headers: Option<&HashMap<String, String>>,
        form: Option<&HashMap<&str, Data>>,
        json: Option<&HashMap<&str, Data>>,
    ) -> Result<Response, Response> {
        Request::do_req(
            Method::Delete,
            url,
            query,
            headers,
            form,
            json,
            None as Option<Body>,
        )
        .await
    }

    async fn do_req<T: Into<Body>>(
        method: Method,
        url: &str,
        query: Option<&HashMap<String, String>>,
        headers: Option<&HashMap<String, String>>,
        form: Option<&HashMap<&str, Data>>,
        json: Option<&HashMap<&str, Data>>,
        body_data: Option<T>,
    ) -> Result<Response, Response> {
        let builder = Self::get_builder_with_headers(headers);
        let client = builder.timeout(Duration::from_secs(24 * 3600)).build()?;
        let mut req = match method {
            Method::Get => client.get(url),
            Method::Delete => client.delete(url),
            Method::Post => client.post(url),
            Method::Put => client.put(url),
            Method::Head => client.head(url),
        };
        if let Some(v) = query {
            req = req.query(v);
        }
        if let Some(v) = form {
            req = req.form(v);
        }
        if let Some(v) = json {
            req = req.json(v);
        }
        if let Some(v) = body_data {
            req = req.body(v.into());
        }
        let resp = req.send().await?;
        let status_code = resp.status();
        let mut error_no = ErrNo::SUCCESS;
        let mut message = "".to_string();
        if status_code.is_client_error() || status_code.is_server_error() {
            error_no = ErrNo::STATUS;
            message = format!("{}", status_code);
        }
        let mut headers = HashMap::new();
        for (k, v) in resp.headers() {
            headers.insert(k.to_string(), String::from_utf8_lossy(v.as_bytes()).into());
        }
        Ok(Response {
            error_no,
            error_message: message,
            result: resp.bytes().await?,
            headers,
        })
    }
}

#[cfg(test)]
mod tests {
    use crate::request::{ErrNo, Request};
    use reqwest::Body;
    use serde_json::json;
    use std::collections::HashMap;

    #[tokio::test]
    async fn test_get() {
        let mut header = HashMap::new();
        header.insert("user-agent".to_string(), "test-user-agent".to_string());
        let mut query = HashMap::new();
        query.insert("a".to_string(), "a".to_string());
        query.insert("b".to_string(), "b".to_string());
        query.insert("c".to_string(), "c".to_string());
        let response = Request::get("https://www.baidu.com", Some(&query), Some(&header)).await;
        match response {
            Ok(e) => {
                println!("{:#?}", e);
            }
            Err(e) => println!("{}", e),
        }
    }

    #[tokio::test]
    async fn test_post_form() {
        let mut form = HashMap::new();
        form.insert("hello", json!(1i16));
        form.insert("hello1", json!("world"));
        let mut json = HashMap::new();
        json.insert("hello", json!(1i64));
        json.insert("hello_json", json!("world"));
        json.insert("data", json!(vec![1u8, 2u8, 3u8] as Vec<u8>));
        let resp = Request::post(
            "https://www.baidu.com",
            None,
            None,
            Some(&form),
            Some(&json),
            None as Option<Body>,
        )
        .await;
        if let Ok(e) = &resp {
            println!("{:#?}", e);
        }
        if let Err(e) = resp {
            assert_eq!(e.error_no, ErrNo::DECODE)
        }
    }
}