zlsrs 0.1.6

Rust 标准库扩展工具集,提供更便捷的使用方式
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
//! HTTP 请求构建器模块
//!
//! 这个模块提供了一个流式 API 来构建 HTTP 请求。通过链式调用,
//! 可以方便地设置请求的各种参数,如请求头、请求体、超时时间等。
//!
//! # 示例
//!
//! ```rust
//! use zlsrs::zhttp::{self, BodyFormat};
//! use std::time::Duration;
//!
//! async fn example() -> Result<(), Box<dyn std::error::Error>> {
//!     let client = zhttp::new();
//!     
//!     // 发送 POST 请求
//!     let response = client.post("https://api.example.com")
//!         .header("Content-Type", "application/json")
//!         .body(r#"{"key": "value"}"#.as_bytes())
//!         .body_format(BodyFormat::Json)
//!         .timeout(Duration::from_secs(30))
//!         .send()
//!         .await?;
//!     
//!     Ok(())
//! }
//! ```

use std::collections::HashMap;
use std::time::Duration;

use crate::zerror::Result;
use crate::zhttp::types::{BodyFormat, Method, Response};
use crate::zhttp::Client;
use base64::engine::Engine;

/// HTTP 请求构建器
///
/// 提供了一个流式 API 来构建 HTTP 请求。每个方法都返回 `self`,
/// 允许链式调用来设置请求的各个属性。
///
/// # 示例
///
/// ```rust
/// use zlsrs::zhttp::Client;
///
/// let client = Client::new();
/// let builder = client.get("https://api.example.com")
///     .header("Authorization", "Bearer token")
///     .timeout(std::time::Duration::from_secs(30));
/// ```
#[derive(Debug, Clone)]
pub struct RequestBuilder {
    pub(crate) method: Method,
    pub(crate) url: String,
    pub(crate) headers: HashMap<String, String>,
    pub(crate) body: Option<Vec<u8>>,
    pub(crate) body_format: Option<BodyFormat>,
    pub(crate) client: Client,
    pub(crate) timeout: Option<Duration>,
    pub(crate) retries: Option<u32>,
    pub(crate) follow_redirects: Option<bool>,
    pub(crate) verify_ssl: Option<bool>,
}

impl RequestBuilder {
    /// 设置请求头
    ///
    /// # 参数
    ///
    /// * `key` - 请求头名称
    /// * `value` - 请求头值
    ///
    /// # 示例
    ///
    /// ```rust
    /// # use zlsrs::zhttp::Client;
    /// let client = Client::new();
    /// let builder = client.get("https://api.example.com")
    ///     .header("Authorization", "Bearer token")
    ///     .header("Accept", "application/json");
    /// ```
    pub fn header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.headers.insert(key.into(), value.into());
        self
    }

    /// 批量设置请求头
    ///
    /// # 参数
    ///
    /// * `headers` - 请求头键值对的迭代器
    ///
    /// # 示例
    ///
    /// ```rust
    /// # use zlsrs::zhttp::Client;
    /// let client = Client::new();
    /// let headers = vec![
    ///     ("Authorization", "Bearer token"),
    ///     ("Accept", "application/json"),
    /// ];
    /// let builder = client.get("https://api.example.com")
    ///     .headers(headers);
    /// ```
    pub fn headers(
        mut self,
        headers: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>,
    ) -> Self {
        for (key, value) in headers {
            self.headers.insert(key.into(), value.into());
        }
        self
    }

    /// 设置请求体
    ///
    /// # 参数
    ///
    /// * `body` - 请求体数据
    ///
    /// # 示例
    ///
    /// ```rust
    /// # use zlsrs::zhttp::Client;
    /// let client = Client::new();
    /// let builder = client.post("https://api.example.com")
    ///     .body("Hello, world!".as_bytes());
    /// ```
    pub fn body(mut self, body: impl Into<Vec<u8>>) -> Self {
        self.body = Some(body.into());
        self
    }

    /// 设置 JSON 请求体
    ///
    /// 自动设置 Content-Type 为 application/json
    ///
    /// # 参数
    ///
    /// * `value` - 实现了 `serde::Serialize` 的值
    ///
    /// # 示例
    ///
    /// ```rust
    /// # use zlsrs::zhttp::Client;
    /// # use serde_json::json;
    /// let client = Client::new();
    /// let data = json!({
    ///     "key": "value",
    ///     "number": 42
    /// });
    /// let builder = client.post("https://api.example.com")
    ///     .json(&data)?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    #[cfg(feature = "json")]
    pub fn json<T: serde::Serialize>(mut self, value: &T) -> Result<Self> {
        let body = serde_json::to_vec(value)?;
        self.body = Some(body);
        self.body_format = Some(BodyFormat::Json);
        Ok(self)
    }

    /// 设置表单请求体
    ///
    /// 自动设置 Content-Type 为 application/x-www-form-urlencoded
    ///
    /// # 参数
    ///
    /// * `data` - 表单数据键值对的迭代器
    ///
    /// # 示例
    ///
    /// ```rust
    /// # use zlsrs::zhttp::Client;
    /// let client = Client::new();
    /// let form_data = vec![
    ///     ("username", "john_doe"),
    ///     ("password", "secret123"),
    /// ];
    /// let builder = client.post("https://api.example.com/login")
    ///     .form(form_data);
    /// ```
    pub fn form(
        mut self,
        data: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>,
    ) -> Self {
        let mut form_data = Vec::new();
        for (key, value) in data {
            if !form_data.is_empty() {
                form_data.push(b'&');
            }
            form_data.extend(urlencoding::encode(&key.into()).as_bytes());
            form_data.push(b'=');
            form_data.extend(urlencoding::encode(&value.into()).as_bytes());
        }
        self.body = Some(form_data);
        self.body_format = Some(BodyFormat::FormUrlEncoded);
        self
    }

    /// 设置请求体格式
    ///
    /// # 参数
    ///
    /// * `format` - 请求体格式
    ///
    /// # 示例
    ///
    /// ```rust
    /// # use zlsrs::zhttp::{Client, BodyFormat};
    /// let client = Client::new();
    /// let builder = client.post("https://api.example.com")
    ///     .body(r#"{"key": "value"}"#.as_bytes())
    ///     .body_format(BodyFormat::Json);
    /// ```
    pub fn body_format(mut self, format: BodyFormat) -> Self {
        self.body_format = Some(format);
        self
    }

    /// 设置请求超时时间
    ///
    /// # 参数
    ///
    /// * `timeout` - 超时时间
    ///
    /// # 示例
    ///
    /// ```rust
    /// # use zlsrs::zhttp::Client;
    /// # use std::time::Duration;
    /// let client = Client::new();
    /// let builder = client.get("https://api.example.com")
    ///     .timeout(Duration::from_secs(30));
    /// ```
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// 设置请求失败时的重试次数
    ///
    /// # 参数
    ///
    /// * `retries` - 重试次数
    ///
    /// # 示例
    ///
    /// ```rust
    /// # use zlsrs::zhttp::Client;
    /// let client = Client::new();
    /// let builder = client.get("https://api.example.com")
    ///     .retries(3);
    /// ```
    pub fn retries(mut self, retries: u32) -> Self {
        self.retries = Some(retries);
        self
    }

    /// 设置是否自动跟随重定向
    ///
    /// # 参数
    ///
    /// * `follow` - 是否跟随重定向
    ///
    /// # 示例
    ///
    /// ```rust
    /// # use zlsrs::zhttp::Client;
    /// let client = Client::new();
    /// let builder = client.get("https://api.example.com")
    ///     .follow_redirects(true);
    /// ```
    pub fn follow_redirects(mut self, follow: bool) -> Self {
        self.follow_redirects = Some(follow);
        self
    }

    /// 设置是否验证 SSL 证书
    ///
    /// # 参数
    ///
    /// * `verify` - 是否验证证书
    ///
    /// # 示例
    ///
    /// ```rust
    /// # use zlsrs::zhttp::Client;
    /// let client = Client::new();
    /// let builder = client.get("https://api.example.com")
    ///     .verify_ssl(true);
    /// ```
    pub fn verify_ssl(mut self, verify: bool) -> Self {
        self.verify_ssl = Some(verify);
        self
    }

    /// 设置基本认证
    ///
    /// # 参数
    ///
    /// * `username` - 用户名
    /// * `password` - 密码
    pub fn basic_auth(self, username: impl Into<String>, password: impl Into<String>) -> Self {
        let auth = format!(
            "Basic {}",
            base64::engine::general_purpose::STANDARD.encode(format!(
                "{}:{}",
                username.into(),
                password.into()
            ))
        );
        self.header("Authorization", auth)
    }

    /// 设置 Bearer token 认证
    ///
    /// # 参数
    ///
    /// * `token` - Bearer token
    pub fn bearer_auth(self, token: impl Into<String>) -> Self {
        self.header("Authorization", format!("Bearer {}", token.into()))
    }

    /// 设置查询参数
    ///
    /// # 参数
    ///
    /// * `params` - 查询参数键值对
    pub fn query(
        mut self,
        params: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>,
    ) -> Self {
        let mut url = self.url;
        let mut first = !url.contains('?');

        for (key, value) in params {
            url.push_str(if first { "?" } else { "&" });
            url.push_str(&urlencoding::encode(&key.into()));
            url.push('=');
            url.push_str(&urlencoding::encode(&value.into()));
            first = false;
        }

        self.url = url;
        self
    }

    /// 设置 multipart/form-data 请求体
    ///
    /// # 参数
    ///
    /// * `parts` - 表单部分的迭代器,每个部分包含名称、内容和可选的文件名
    pub fn multipart(
        mut self,
        parts: impl IntoIterator<Item = (String, Vec<u8>, Option<String>)>,
    ) -> Self {
        let boundary = format!("------------------------{}", uuid::Uuid::new_v4());
        let mut body = Vec::new();

        for (name, content, filename) in parts {
            body.extend_from_slice(b"--");
            body.extend_from_slice(boundary.as_bytes());
            body.extend_from_slice(b"\r\n");

            // Content-Disposition header
            body.extend_from_slice(b"Content-Disposition: form-data; name=\"");
            body.extend_from_slice(name.as_bytes());
            body.extend_from_slice(b"\"");

            if let Some(filename) = filename {
                body.extend_from_slice(b"; filename=\"");
                body.extend_from_slice(filename.as_bytes());
                body.extend_from_slice(b"\"");
            }

            body.extend_from_slice(b"\r\n\r\n");
            body.extend_from_slice(&content);
            body.extend_from_slice(b"\r\n");
        }

        // Add final boundary
        body.extend_from_slice(b"--");
        body.extend_from_slice(boundary.as_bytes());
        body.extend_from_slice(b"--\r\n");

        self.body = Some(body);
        self.body_format = Some(BodyFormat::FormData(boundary));
        self
    }

    /// 设置请求体为 JSON 字符串
    pub fn json_str(self, json: impl Into<String>) -> Self {
        self.body(json.into().into_bytes())
            .body_format(BodyFormat::Json)
    }

    /// 设置压缩方式
    pub fn compression(self, compression: bool) -> Self {
        if compression {
            self.header("Accept-Encoding", "gzip, deflate")
        } else {
            self
        }
    }

    /// 设置是否保持连接
    pub fn keep_alive(self, keep_alive: bool) -> Self {
        self.header(
            "Connection",
            if keep_alive { "keep-alive" } else { "close" },
        )
    }

    /// 发送 HTTP 请求
    ///
    /// 使用已配置的参数发送请求,并返回响应结果
    ///
    /// # 返回值
    ///
    /// 返回 `Result<Response>`,其中:
    /// - `Ok(Response)` - 请求成功,返回响应对象
    /// - `Err(Error)` - 请求失败,返回错误信息
    ///
    /// # 示例
    ///
    /// ```rust
    /// # use zlsrs::zhttp::Client;
    /// async fn example() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = Client::new();
    ///     let response = client.get("https://api.example.com")
    ///         .send()
    ///         .await?;
    ///     
    ///     println!("Status: {}", response.status);
    ///     Ok(())
    /// }
    /// ```
    pub fn send(self) -> Result<Response> {
        let client = self.client.clone();
        client.send_request(self).map_err(|e| e.into())
    }
}