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