Skip to main content

yang_base/http/
request.rs

1//! HTTP 请求构建器实现
2//!
3//! 提供链式调用接口构建 HTTP 请求。
4
5use crate::error::BaseError;
6use crate::http::response::Response;
7use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
8use reqwest::{Client, Method};
9use serde::Serialize;
10use std::time::Duration;
11
12/// HTTP 请求构建器
13///
14/// 提供链式调用接口构建 HTTP 请求。
15///
16/// # Header 错误处理
17///
18/// `header`、`headers` 等方法在解析失败时不会立即返回错误,而是将错误信息
19/// 累积到内部 `header_errors` 列表中。调用 `send()` 时,若存在累积的 header
20/// 错误,则返回 `BaseError::ParamInvalid("header", ...)` 而不发送请求。
21///
22/// # 示例
23///
24/// ```rust,ignore
25/// use yang_base::http::HttpClient;
26///
27/// let response = HttpClient::global()?
28///     .get("https://api.example.com/users")
29///     .header("X-Custom-Header", "value")
30///     .query("page", "1")
31///     .bearer_token("your_token")
32///     .timeout(60)
33///     .send()
34///     .await?;
35/// ```
36pub struct RequestBuilder {
37    /// reqwest 客户端(Arc 包装,clone 时复用同一连接池)
38    client: Client,
39
40    /// HTTP 方法
41    method: Method,
42
43    /// 请求 URL
44    url: String,
45
46    /// 请求头
47    headers: HeaderMap,
48
49    /// 累积的 header 解析错误列表
50    ///
51    /// `header`、`headers` 方法在解析失败时将错误描述追加到此列表,
52    /// `send()` 时若非空则返回 `BaseError::ParamInvalid`。
53    header_errors: Vec<String>,
54
55    /// 查询参数
56    query_params: Vec<(String, String)>,
57
58    /// 请求体
59    body: Option<Vec<u8>>,
60
61    /// 超时时间
62    timeout: Duration,
63
64    /// Token(可选)
65    token: Option<String>,
66}
67
68impl RequestBuilder {
69    /// 创建新的请求构建器
70    ///
71    /// # 参数
72    ///
73    /// - `client`: reqwest 客户端(Arc 包装,clone 时复用同一连接池)
74    /// - `method`: HTTP 方法
75    /// - `url`: 请求 URL
76    /// - `timeout`: 超时时间
77    /// - `token`: 默认 Token
78    pub(crate) fn new(
79        client: Client,
80        method: Method,
81        url: String,
82        timeout: Duration,
83        token: Option<String>,
84    ) -> Self {
85        Self {
86            client,
87            method,
88            url,
89            headers: HeaderMap::new(),
90            header_errors: Vec::new(),
91            query_params: Vec::new(),
92            body: None,
93            timeout,
94            token,
95        }
96    }
97
98    /// 设置请求头
99    ///
100    /// 若 header 名称或值解析失败,错误信息将被累积到内部错误列表,
101    /// 不会立即返回错误。调用 `send()` 时若存在累积错误则返回 `BaseError::ParamInvalid`。
102    ///
103    /// # 参数
104    ///
105    /// - `name`: 请求头名称
106    /// - `value`: 请求头值
107    ///
108    /// # 示例
109    ///
110    /// ```rust,ignore
111    /// let response = client
112    ///     .get("https://api.example.com/users")
113    ///     .header("X-Custom-Header", "value")
114    ///     .send()
115    ///     .await?;
116    /// ```
117    pub fn header(mut self, name: &str, value: &str) -> Self {
118        // 解析 header 名称
119        let header_name = match HeaderName::from_bytes(name.as_bytes()) {
120            Ok(n) => n,
121            Err(e) => {
122                // 累积错误,不立即返回
123                self.header_errors
124                    .push(format!("非法 header 名称 '{}': {}", name, e));
125                return self;
126            }
127        };
128
129        // 解析 header 值
130        let header_value = match HeaderValue::from_str(value) {
131            Ok(v) => v,
132            Err(e) => {
133                // 累积错误,不立即返回
134                self.header_errors
135                    .push(format!("非法 header 值 '{}': {}", value, e));
136                return self;
137            }
138        };
139
140        self.headers.insert(header_name, header_value);
141        self
142    }
143
144    /// 批量设置请求头
145    ///
146    /// 若任意 header 名称或值解析失败,错误信息将被累积到内部错误列表,
147    /// 不会立即返回错误。调用 `send()` 时若存在累积错误则返回 `BaseError::ParamInvalid`。
148    ///
149    /// # 参数
150    ///
151    /// - `headers`: 请求头列表
152    ///
153    /// # 示例
154    ///
155    /// ```rust,ignore
156    /// let response = client
157    ///     .get("https://api.example.com/users")
158    ///     .headers(vec![
159    ///         ("X-Custom-Header-1", "value1"),
160    ///         ("X-Custom-Header-2", "value2"),
161    ///     ])
162    ///     .send()
163    ///     .await?;
164    /// ```
165    pub fn headers(mut self, headers: Vec<(&str, &str)>) -> Self {
166        for (name, value) in headers {
167            // 解析 header 名称
168            let header_name = match HeaderName::from_bytes(name.as_bytes()) {
169                Ok(n) => n,
170                Err(e) => {
171                    // 累积错误,继续处理其余 header
172                    self.header_errors
173                        .push(format!("非法 header 名称 '{}': {}", name, e));
174                    continue;
175                }
176            };
177
178            // 解析 header 值
179            let header_value = match HeaderValue::from_str(value) {
180                Ok(v) => v,
181                Err(e) => {
182                    // 累积错误,继续处理其余 header
183                    self.header_errors
184                        .push(format!("非法 header 值 '{}': {}", value, e));
185                    continue;
186                }
187            };
188
189            self.headers.insert(header_name, header_value);
190        }
191        self
192    }
193
194    /// 设置 Content-Type
195    ///
196    /// # 参数
197    ///
198    /// - `content_type`: Content-Type 值
199    ///
200    /// # 示例
201    ///
202    /// ```rust,ignore
203    /// let response = client
204    ///     .post("https://api.example.com/users")
205    ///     .content_type("application/json")
206    ///     .send()
207    ///     .await?;
208    /// ```
209    pub fn content_type(self, content_type: &str) -> Self {
210        self.header("Content-Type", content_type)
211    }
212
213    /// 设置 Bearer Token
214    ///
215    /// # 参数
216    ///
217    /// - `token`: Token 字符串
218    ///
219    /// # 示例
220    ///
221    /// ```rust,ignore
222    /// let response = client
223    ///     .get("https://api.example.com/users")
224    ///     .bearer_token("your_token")
225    ///     .send()
226    ///     .await?;
227    /// ```
228    pub fn bearer_token(mut self, token: &str) -> Self {
229        self.token = Some(token.to_string());
230        self
231    }
232
233    /// 设置 User-Agent
234    ///
235    /// # 参数
236    ///
237    /// - `user_agent`: User-Agent 值
238    ///
239    /// # 示例
240    ///
241    /// ```rust,ignore
242    /// let response = client
243    ///     .get("https://api.example.com/users")
244    ///     .user_agent("MyApp/1.0")
245    ///     .send()
246    ///     .await?;
247    /// ```
248    pub fn user_agent(self, user_agent: &str) -> Self {
249        self.header("User-Agent", user_agent)
250    }
251
252    /// 添加查询参数
253    ///
254    /// # 参数
255    ///
256    /// - `key`: 参数名
257    /// - `value`: 参数值
258    ///
259    /// # 示例
260    ///
261    /// ```rust,ignore
262    /// let response = client
263    ///     .get("https://api.example.com/users")
264    ///     .query("page", "1")
265    ///     .query("limit", "10")
266    ///     .send()
267    ///     .await?;
268    /// ```
269    pub fn query(mut self, key: &str, value: &str) -> Self {
270        self.query_params.push((key.to_string(), value.to_string()));
271        self
272    }
273
274    /// 批量添加查询参数
275    ///
276    /// # 参数
277    ///
278    /// - `params`: 查询参数列表
279    ///
280    /// # 示例
281    ///
282    /// ```rust,ignore
283    /// let response = client
284    ///     .get("https://api.example.com/users")
285    ///     .queries(vec![("page", "1"), ("limit", "10")])
286    ///     .send()
287    ///     .await?;
288    /// ```
289    pub fn queries(mut self, params: Vec<(&str, &str)>) -> Self {
290        for (key, value) in params {
291            self.query_params.push((key.to_string(), value.to_string()));
292        }
293        self
294    }
295
296    /// 设置 JSON 请求体
297    ///
298    /// # 参数
299    ///
300    /// - `json`: 可序列化为 JSON 的数据
301    ///
302    /// # 返回
303    ///
304    /// - `Ok(Self)`: 设置成功
305    /// - `Err(BaseError)`: 序列化失败
306    ///
307    /// # 示例
308    ///
309    /// ```rust,ignore
310    /// #[derive(Serialize)]
311    /// struct User {
312    ///     name: String,
313    ///     email: String,
314    /// }
315    ///
316    /// let user = User {
317    ///     name: "Alice".to_string(),
318    ///     email: "alice@example.com".to_string(),
319    /// };
320    ///
321    /// let response = client
322    ///     .post("https://api.example.com/users")
323    ///     .json(&user)?
324    ///     .send()
325    ///     .await?;
326    /// ```
327    pub fn json<T: Serialize>(mut self, json: &T) -> Result<Self, BaseError> {
328        let json_bytes =
329            serde_json::to_vec(json).map_err(|e| BaseError::JsonSerializeFailed(e.to_string()))?;
330
331        self.body = Some(json_bytes);
332        self = self.content_type("application/json");
333
334        Ok(self)
335    }
336
337    /// 设置表单请求体
338    ///
339    /// 使用 `serde_urlencoded` 对表单数据进行 URL 编码,正确处理特殊字符、
340    /// 空格、UTF-8 字符等,并自动设置 `Content-Type: application/x-www-form-urlencoded`。
341    ///
342    /// # 参数
343    ///
344    /// - `form`: 表单数据(键值对列表)
345    ///
346    /// # 示例
347    ///
348    /// ```rust,ignore
349    /// let response = client
350    ///     .post("https://api.example.com/login")
351    ///     .form(vec![("username", "alice"), ("password", "secret")])
352    ///     .send()
353    ///     .await?;
354    /// ```
355    pub fn form(mut self, form: Vec<(&str, &str)>) -> Self {
356        // 使用 serde_urlencoded 进行标准 URL 编码,正确处理特殊字符
357        match serde_urlencoded::to_string(&form) {
358            Ok(encoded) => {
359                self.body = Some(encoded.into_bytes());
360                // 自动设置 Content-Type
361                self = self.content_type("application/x-www-form-urlencoded");
362            }
363            Err(e) => {
364                // 编码失败时累积错误
365                self.header_errors
366                    .push(format!("表单数据编码失败: {}", e));
367            }
368        }
369        self
370    }
371
372    /// 设置原始字节请求体
373    ///
374    /// # 参数
375    ///
376    /// - `body`: 字节数据
377    ///
378    /// # 示例
379    ///
380    /// ```rust,ignore
381    /// let response = client
382    ///     .post("https://api.example.com/upload")
383    ///     .body(vec![0x00, 0x01, 0x02])
384    ///     .send()
385    ///     .await?;
386    /// ```
387    pub fn body(mut self, body: Vec<u8>) -> Self {
388        self.body = Some(body);
389        self
390    }
391
392    /// 设置文本请求体
393    ///
394    /// # 参数
395    ///
396    /// - `text`: 文本数据
397    ///
398    /// # 示例
399    ///
400    /// ```rust,ignore
401    /// let response = client
402    ///     .post("https://api.example.com/notes")
403    ///     .text("Hello, World!")
404    ///     .send()
405    ///     .await?;
406    /// ```
407    pub fn text(mut self, text: &str) -> Self {
408        self.body = Some(text.as_bytes().to_vec());
409        self = self.content_type("text/plain");
410        self
411    }
412
413    /// 设置超时时间
414    ///
415    /// # 参数
416    ///
417    /// - `timeout_secs`: 超时时间(秒)
418    ///
419    /// # 示例
420    ///
421    /// ```rust,ignore
422    /// let response = client
423    ///     .get("https://api.example.com/users")
424    ///     .timeout(60)
425    ///     .send()
426    ///     .await?;
427    /// ```
428    pub fn timeout(mut self, timeout_secs: u64) -> Self {
429        self.timeout = Duration::from_secs(timeout_secs);
430        self
431    }
432
433    /// 发送请求
434    ///
435    /// 在发送前检查累积的 header 错误。若存在任何 header 解析错误,
436    /// 则返回 `BaseError::ParamInvalid("header", ...)` 而不发送请求。
437    ///
438    /// # 返回
439    ///
440    /// - `Ok(Response)`: 响应对象
441    /// - `Err(BaseError::ParamInvalid)`: 存在非法 header
442    /// - `Err(BaseError::HttpRequestFailed)`: 请求发送失败
443    ///
444    /// # 示例
445    ///
446    /// ```rust,ignore
447    /// let response = client
448    ///     .get("https://api.example.com/users")
449    ///     .send()
450    ///     .await?;
451    /// ```
452    pub async fn send(self) -> Result<Response, BaseError> {
453        // 检查累积的 header 错误,若非空则提前返回错误
454        if !self.header_errors.is_empty() {
455            return Err(BaseError::ParamInvalid(
456                "header".to_string(),
457                self.header_errors.join("; "),
458            ));
459        }
460
461        // 构建请求
462        // 注意:self.client.clone() 是 Arc::clone,复用同一底层连接池,不创建新的 TCP 连接池
463        let mut request = self
464            .client
465            .request(self.method, &self.url)
466            .timeout(self.timeout);
467
468        // 添加请求头
469        request = request.headers(self.headers);
470
471        // 添加 Token
472        if let Some(token) = self.token {
473            request = request.bearer_auth(token);
474        }
475
476        // 添加查询参数
477        if !self.query_params.is_empty() {
478            request = request.query(&self.query_params);
479        }
480
481        // 添加请求体
482        if let Some(body) = self.body {
483            request = request.body(body);
484        }
485
486        // 发送请求
487        let response = request
488            .send()
489            .await
490            .map_err(BaseError::HttpRequestFailed)?;
491
492        Ok(Response::new(response))
493    }
494}