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/// # 示例
17///
18/// ```rust,ignore
19/// use yang_base::http::HttpClient;
20///
21/// let response = HttpClient::global()?
22/// .get("https://api.example.com/users")
23/// .header("X-Custom-Header", "value")
24/// .query("page", "1")
25/// .bearer_token("your_token")
26/// .timeout(60)
27/// .send()
28/// .await?;
29/// ```
30pub struct RequestBuilder {
31 /// reqwest 客户端
32 client: Client,
33
34 /// HTTP 方法
35 method: Method,
36
37 /// 请求 URL
38 url: String,
39
40 /// 请求头
41 headers: HeaderMap,
42
43 /// 查询参数
44 query_params: Vec<(String, String)>,
45
46 /// 请求体
47 body: Option<Vec<u8>>,
48
49 /// 超时时间
50 timeout: Duration,
51
52 /// Token(可选)
53 token: Option<String>,
54}
55
56impl RequestBuilder {
57 /// 创建新的请求构建器
58 ///
59 /// # 参数
60 ///
61 /// - `client`: reqwest 客户端
62 /// - `method`: HTTP 方法
63 /// - `url`: 请求 URL
64 /// - `timeout`: 超时时间
65 /// - `token`: 默认 Token
66 pub(crate) fn new(
67 client: Client,
68 method: Method,
69 url: String,
70 timeout: Duration,
71 token: Option<String>,
72 ) -> Self {
73 Self {
74 client,
75 method,
76 url,
77 headers: HeaderMap::new(),
78 query_params: Vec::new(),
79 body: None,
80 timeout,
81 token,
82 }
83 }
84
85 /// 设置请求头
86 ///
87 /// # 参数
88 ///
89 /// - `name`: 请求头名称
90 /// - `value`: 请求头值
91 ///
92 /// # 示例
93 ///
94 /// ```rust,ignore
95 /// let response = client
96 /// .get("https://api.example.com/users")
97 /// .header("X-Custom-Header", "value")
98 /// .send()
99 /// .await?;
100 /// ```
101 pub fn header(mut self, name: &str, value: &str) -> Self {
102 if let (Ok(name), Ok(value)) = (
103 HeaderName::from_bytes(name.as_bytes()),
104 HeaderValue::from_str(value),
105 ) {
106 self.headers.insert(name, value);
107 }
108 self
109 }
110
111 /// 批量设置请求头
112 ///
113 /// # 参数
114 ///
115 /// - `headers`: 请求头列表
116 ///
117 /// # 示例
118 ///
119 /// ```rust,ignore
120 /// let response = client
121 /// .get("https://api.example.com/users")
122 /// .headers(vec![
123 /// ("X-Custom-Header-1", "value1"),
124 /// ("X-Custom-Header-2", "value2"),
125 /// ])
126 /// .send()
127 /// .await?;
128 /// ```
129 pub fn headers(mut self, headers: Vec<(&str, &str)>) -> Self {
130 for (name, value) in headers {
131 if let (Ok(name), Ok(value)) = (
132 HeaderName::from_bytes(name.as_bytes()),
133 HeaderValue::from_str(value),
134 ) {
135 self.headers.insert(name, value);
136 }
137 }
138 self
139 }
140
141 /// 设置 Content-Type
142 ///
143 /// # 参数
144 ///
145 /// - `content_type`: Content-Type 值
146 ///
147 /// # 示例
148 ///
149 /// ```rust,ignore
150 /// let response = client
151 /// .post("https://api.example.com/users")
152 /// .content_type("application/json")
153 /// .send()
154 /// .await?;
155 /// ```
156 pub fn content_type(self, content_type: &str) -> Self {
157 self.header("Content-Type", content_type)
158 }
159
160 /// 设置 Bearer Token
161 ///
162 /// # 参数
163 ///
164 /// - `token`: Token 字符串
165 ///
166 /// # 示例
167 ///
168 /// ```rust,ignore
169 /// let response = client
170 /// .get("https://api.example.com/users")
171 /// .bearer_token("your_token")
172 /// .send()
173 /// .await?;
174 /// ```
175 pub fn bearer_token(mut self, token: &str) -> Self {
176 self.token = Some(token.to_string());
177 self
178 }
179
180 /// 设置 User-Agent
181 ///
182 /// # 参数
183 ///
184 /// - `user_agent`: User-Agent 值
185 ///
186 /// # 示例
187 ///
188 /// ```rust,ignore
189 /// let response = client
190 /// .get("https://api.example.com/users")
191 /// .user_agent("MyApp/1.0")
192 /// .send()
193 /// .await?;
194 /// ```
195 pub fn user_agent(self, user_agent: &str) -> Self {
196 self.header("User-Agent", user_agent)
197 }
198
199 /// 添加查询参数
200 ///
201 /// # 参数
202 ///
203 /// - `key`: 参数名
204 /// - `value`: 参数值
205 ///
206 /// # 示例
207 ///
208 /// ```rust,ignore
209 /// let response = client
210 /// .get("https://api.example.com/users")
211 /// .query("page", "1")
212 /// .query("limit", "10")
213 /// .send()
214 /// .await?;
215 /// ```
216 pub fn query(mut self, key: &str, value: &str) -> Self {
217 self.query_params.push((key.to_string(), value.to_string()));
218 self
219 }
220
221 /// 批量添加查询参数
222 ///
223 /// # 参数
224 ///
225 /// - `params`: 查询参数列表
226 ///
227 /// # 示例
228 ///
229 /// ```rust,ignore
230 /// let response = client
231 /// .get("https://api.example.com/users")
232 /// .queries(vec![("page", "1"), ("limit", "10")])
233 /// .send()
234 /// .await?;
235 /// ```
236 pub fn queries(mut self, params: Vec<(&str, &str)>) -> Self {
237 for (key, value) in params {
238 self.query_params.push((key.to_string(), value.to_string()));
239 }
240 self
241 }
242
243 /// 设置 JSON 请求体
244 ///
245 /// # 参数
246 ///
247 /// - `json`: 可序列化为 JSON 的数据
248 ///
249 /// # 返回
250 ///
251 /// - `Ok(Self)`: 设置成功
252 /// - `Err(BaseError)`: 序列化失败
253 ///
254 /// # 示例
255 ///
256 /// ```rust,ignore
257 /// #[derive(Serialize)]
258 /// struct User {
259 /// name: String,
260 /// email: String,
261 /// }
262 ///
263 /// let user = User {
264 /// name: "Alice".to_string(),
265 /// email: "alice@example.com".to_string(),
266 /// };
267 ///
268 /// let response = client
269 /// .post("https://api.example.com/users")
270 /// .json(&user)?
271 /// .send()
272 /// .await?;
273 /// ```
274 pub fn json<T: Serialize>(mut self, json: &T) -> Result<Self, BaseError> {
275 let json_str =
276 serde_json::to_vec(json).map_err(|e| BaseError::JsonSerializeFailed(e.to_string()))?;
277
278 self.body = Some(json_str);
279 self = self.content_type("application/json");
280
281 Ok(self)
282 }
283
284 /// 设置表单请求体
285 ///
286 /// # 参数
287 ///
288 /// - `form`: 表单数据
289 ///
290 /// # 示例
291 ///
292 /// ```rust,ignore
293 /// let response = client
294 /// .post("https://api.example.com/login")
295 /// .form(vec![("username", "alice"), ("password", "secret")])
296 /// .send()
297 /// .await?;
298 /// ```
299 pub fn form(mut self, form: Vec<(&str, &str)>) -> Self {
300 let form_str = form
301 .iter()
302 .map(|(k, v)| format!("{}={}", k, v))
303 .collect::<Vec<_>>()
304 .join("&");
305
306 self.body = Some(form_str.into_bytes());
307 self = self.content_type("application/x-www-form-urlencoded");
308
309 self
310 }
311
312 /// 设置原始字节请求体
313 ///
314 /// # 参数
315 ///
316 /// - `body`: 字节数据
317 ///
318 /// # 示例
319 ///
320 /// ```rust,ignore
321 /// let response = client
322 /// .post("https://api.example.com/upload")
323 /// .body(vec![0x00, 0x01, 0x02])
324 /// .send()
325 /// .await?;
326 /// ```
327 pub fn body(mut self, body: Vec<u8>) -> Self {
328 self.body = Some(body);
329 self
330 }
331
332 /// 设置文本请求体
333 ///
334 /// # 参数
335 ///
336 /// - `text`: 文本数据
337 ///
338 /// # 示例
339 ///
340 /// ```rust,ignore
341 /// let response = client
342 /// .post("https://api.example.com/notes")
343 /// .text("Hello, World!")
344 /// .send()
345 /// .await?;
346 /// ```
347 pub fn text(mut self, text: &str) -> Self {
348 self.body = Some(text.as_bytes().to_vec());
349 self = self.content_type("text/plain");
350 self
351 }
352
353 /// 设置超时时间
354 ///
355 /// # 参数
356 ///
357 /// - `timeout_secs`: 超时时间(秒)
358 ///
359 /// # 示例
360 ///
361 /// ```rust,ignore
362 /// let response = client
363 /// .get("https://api.example.com/users")
364 /// .timeout(60)
365 /// .send()
366 /// .await?;
367 /// ```
368 pub fn timeout(mut self, timeout_secs: u64) -> Self {
369 self.timeout = Duration::from_secs(timeout_secs);
370 self
371 }
372
373 /// 发送请求
374 ///
375 /// # 返回
376 ///
377 /// - `Ok(Response)`: 响应对象
378 /// - `Err(BaseError)`: 请求失败
379 ///
380 /// # 示例
381 ///
382 /// ```rust,ignore
383 /// let response = client
384 /// .get("https://api.example.com/users")
385 /// .send()
386 /// .await?;
387 /// ```
388 pub async fn send(self) -> Result<Response, BaseError> {
389 // 构建请求
390 let mut request = self
391 .client
392 .request(self.method, &self.url)
393 .timeout(self.timeout);
394
395 // 添加请求头
396 request = request.headers(self.headers);
397
398 // 添加 Token
399 if let Some(token) = self.token {
400 request = request.bearer_auth(token);
401 }
402
403 // 添加查询参数
404 if !self.query_params.is_empty() {
405 request = request.query(&self.query_params);
406 }
407
408 // 添加请求体
409 if let Some(body) = self.body {
410 request = request.body(body);
411 }
412
413 // 发送请求
414 let response = request
415 .send()
416 .await
417 .map_err(|e| BaseError::HttpRequestFailed(e.to_string()))?;
418
419 Ok(Response::new(response))
420 }
421}