Skip to main content

yang_base/http/
response.rs

1//! HTTP 响应处理实现
2//!
3//! 提供便捷的响应处理方法。
4
5use crate::error::BaseError;
6use reqwest::header::HeaderMap;
7use reqwest::Response as ReqwestResponse;
8
9/// HTTP 响应
10///
11/// 封装 reqwest::Response,提供便捷的响应处理方法
12///
13/// # 示例
14///
15/// ```rust,ignore
16/// use yang_base::http::HttpClient;
17///
18/// let response = HttpClient::global()?
19///     .get("https://api.example.com/users")
20///     .send()
21///     .await?;
22///
23/// // 检查状态码
24/// if response.is_success() {
25///     // 解析 JSON
26///     let users: Vec<User> = response.json().await?;
27/// }
28/// ```
29pub struct Response {
30    /// reqwest 响应
31    response: ReqwestResponse,
32}
33
34impl Response {
35    /// 创建新的响应对象
36    ///
37    /// # 参数
38    ///
39    /// - `response`: reqwest 响应
40    pub(crate) fn new(response: ReqwestResponse) -> Self {
41        Self { response }
42    }
43
44    /// 获取状态码
45    ///
46    /// # 返回
47    ///
48    /// - HTTP 状态码
49    ///
50    /// # 示例
51    ///
52    /// ```rust,ignore
53    /// let status = response.status();
54    /// println!("状态码: {}", status);
55    /// ```
56    pub fn status(&self) -> u16 {
57        self.response.status().as_u16()
58    }
59
60    /// 检查响应是否成功(2xx)
61    ///
62    /// # 返回
63    ///
64    /// - `true`: 状态码为 2xx
65    /// - `false`: 状态码不是 2xx
66    ///
67    /// # 示例
68    ///
69    /// ```rust,ignore
70    /// if response.is_success() {
71    ///     println!("请求成功");
72    /// } else {
73    ///     println!("请求失败,状态码: {}", response.status());
74    /// }
75    /// ```
76    pub fn is_success(&self) -> bool {
77        self.response.status().is_success()
78    }
79
80    /// 获取响应头
81    ///
82    /// # 返回
83    ///
84    /// - 响应头映射
85    ///
86    /// # 示例
87    ///
88    /// ```rust,ignore
89    /// let headers = response.headers();
90    /// if let Some(content_type) = headers.get("content-type") {
91    ///     println!("Content-Type: {:?}", content_type);
92    /// }
93    /// ```
94    pub fn headers(&self) -> &HeaderMap {
95        self.response.headers()
96    }
97
98    /// 获取响应体为文本
99    ///
100    /// # 返回
101    ///
102    /// - `Ok(String)`: 响应文本
103    /// - `Err(BaseError)`: 解析失败
104    ///
105    /// # 示例
106    ///
107    /// ```rust,ignore
108    /// let text = response.text().await?;
109    /// println!("响应内容: {}", text);
110    /// ```
111    pub async fn text(self) -> Result<String, BaseError> {
112        self.response
113            .text()
114            .await
115            .map_err(|e| BaseError::HttpResponseParseFailed(e.to_string()))
116    }
117
118    /// 获取响应体为字节流
119    ///
120    /// # 返回
121    ///
122    /// - `Ok(Vec<u8>)`: 响应字节
123    /// - `Err(BaseError)`: 解析失败
124    ///
125    /// # 示例
126    ///
127    /// ```rust,ignore
128    /// let bytes = response.bytes().await?;
129    /// println!("响应大小: {} 字节", bytes.len());
130    /// ```
131    pub async fn bytes(self) -> Result<Vec<u8>, BaseError> {
132        self.response
133            .bytes()
134            .await
135            .map(|b| b.to_vec())
136            .map_err(|e| BaseError::HttpResponseParseFailed(e.to_string()))
137    }
138
139    /// 获取响应体为 JSON
140    ///
141    /// # 类型参数
142    ///
143    /// - `T`: 目标类型,必须实现 `serde::de::DeserializeOwned`
144    ///
145    /// # 返回
146    ///
147    /// - `Ok(T)`: 反序列化后的对象
148    /// - `Err(BaseError)`: 解析失败
149    ///
150    /// # 示例
151    ///
152    /// ```rust,ignore
153    /// #[derive(Deserialize)]
154    /// struct User {
155    ///     id: u64,
156    ///     name: String,
157    /// }
158    ///
159    /// let user: User = response.json().await?;
160    /// println!("用户: {} (ID: {})", user.name, user.id);
161    /// ```
162    pub async fn json<T: serde::de::DeserializeOwned>(self) -> Result<T, BaseError> {
163        self.response
164            .json()
165            .await
166            .map_err(|e| BaseError::JsonDeserializeFailed(e.to_string()))
167    }
168}