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 /// 响应体最大允许字节数(0 表示已由调用方保证不会为 0;由 HttpClientConfig 注入)
33 max_response_bytes: usize,
34}
35
36impl Response {
37 /// 创建新的响应对象
38 ///
39 /// # 参数
40 ///
41 /// - `response`: reqwest 响应
42 /// - `max_response_bytes`: 响应体最大允许字节数(由 HttpClientConfig 注入)
43 pub(crate) fn new(response: ReqwestResponse, max_response_bytes: usize) -> Self {
44 Self {
45 response,
46 max_response_bytes,
47 }
48 }
49
50 /// 获取状态码
51 ///
52 /// # 返回
53 ///
54 /// - HTTP 状态码
55 ///
56 /// # 示例
57 ///
58 /// ```rust,ignore
59 /// let status = response.status();
60 /// println!("状态码: {}", status);
61 /// ```
62 pub fn status(&self) -> u16 {
63 self.response.status().as_u16()
64 }
65
66 /// 检查响应是否成功(2xx)
67 ///
68 /// # 返回
69 ///
70 /// - `true`: 状态码为 2xx
71 /// - `false`: 状态码不是 2xx
72 ///
73 /// # 示例
74 ///
75 /// ```rust,ignore
76 /// if response.is_success() {
77 /// println!("请求成功");
78 /// } else {
79 /// println!("请求失败,状态码: {}", response.status());
80 /// }
81 /// ```
82 pub fn is_success(&self) -> bool {
83 self.response.status().is_success()
84 }
85
86 /// 获取响应头
87 ///
88 /// # 返回
89 ///
90 /// - 响应头映射
91 ///
92 /// # 示例
93 ///
94 /// ```rust,ignore
95 /// let headers = response.headers();
96 /// if let Some(content_type) = headers.get("content-type") {
97 /// println!("Content-Type: {:?}", content_type);
98 /// }
99 /// ```
100 pub fn headers(&self) -> &HeaderMap {
101 self.response.headers()
102 }
103
104 /// 获取本次响应最终落地的 URL。
105 ///
106 /// 跟随重定向时返回最后一跳的 URL,便于调用方在 opt-in 场景下复核目标
107 /// host。该访问器只读;日志仍由请求侧统一脱敏(移除 query 与 userinfo),
108 /// 请勿把未脱敏的 URL 直接写入日志。
109 ///
110 /// # 返回
111 ///
112 /// - 最终 URL 字符串
113 ///
114 /// # 示例
115 ///
116 /// ```rust,ignore
117 /// let final_url = response.url();
118 /// println!("最终地址: {}", final_url);
119 /// ```
120 pub fn url(&self) -> &str {
121 self.response.url().as_str()
122 }
123
124 /// 获取响应体为文本
125 ///
126 /// # 返回
127 ///
128 /// - `Ok(String)`: 响应文本
129 /// - `Err(BaseError)`: 解析失败
130 ///
131 /// # 示例
132 ///
133 /// ```rust,ignore
134 /// let text = response.text().await?;
135 /// println!("响应内容: {}", text);
136 /// ```
137 pub async fn text(self) -> Result<String, BaseError> {
138 // 必须在 read_body_limited() 消耗 self 之前取出 charset,保留现 charset feature 语义。
139 let charset = self
140 .response
141 .headers()
142 .get(reqwest::header::CONTENT_TYPE)
143 .and_then(|v| v.to_str().ok())
144 .and_then(|v| v.split(';').find_map(|p| p.trim().strip_prefix("charset=")))
145 .and_then(|label| encoding_rs::Encoding::for_label(label.trim().as_bytes()))
146 .unwrap_or(encoding_rs::UTF_8);
147 let body = self.read_body_limited().await?;
148 let (text, _, _) = charset.decode(&body);
149 Ok(text.into_owned())
150 }
151
152 /// 获取响应体为字节流
153 ///
154 /// # 返回
155 ///
156 /// - `Ok(Vec<u8>)`: 响应字节
157 /// - `Err(BaseError)`: 解析失败
158 ///
159 /// # 示例
160 ///
161 /// ```rust,ignore
162 /// let bytes = response.bytes().await?;
163 /// println!("响应大小: {} 字节", bytes.len());
164 /// ```
165 pub async fn bytes(self) -> Result<Vec<u8>, BaseError> {
166 self.read_body_limited().await
167 }
168
169 /// 获取响应体为 JSON
170 ///
171 /// # 类型参数
172 ///
173 /// - `T`: 目标类型,必须实现 `serde::de::DeserializeOwned`
174 ///
175 /// # 返回
176 ///
177 /// - `Ok(T)`: 反序列化后的对象
178 /// - `Err(BaseError)`: 解析失败
179 ///
180 /// # 示例
181 ///
182 /// ```rust,ignore
183 /// #[derive(Deserialize)]
184 /// struct User {
185 /// id: u64,
186 /// name: String,
187 /// }
188 ///
189 /// let user: User = response.json().await?;
190 /// println!("用户: {} (ID: {})", user.name, user.id);
191 /// ```
192 pub async fn json<T: serde::de::DeserializeOwned>(self) -> Result<T, BaseError> {
193 let body = self.read_body_limited().await?;
194 serde_json::from_slice(&body).map_err(|e| BaseError::JsonDeserializeFailed(e.to_string()))
195 }
196
197 /// 按上限流式读取响应体。
198 ///
199 /// 上游可能省略(chunked)或谎报 Content-Length,因此头部预检只做快速失败,
200 /// 真正的硬上限由下面的运行中累计校验保证(验证需求: M12)。
201 async fn read_body_limited(mut self) -> Result<Vec<u8>, BaseError> {
202 let limit = self.max_response_bytes;
203 if let Some(len) = self.response.content_length() {
204 if len > limit as u64 {
205 return Err(BaseError::HttpResponseTooLarge {
206 limit,
207 actual: Some(len),
208 });
209 }
210 }
211 let mut buf: Vec<u8> = Vec::with_capacity(limit.min(64 * 1024));
212 while let Some(chunk) = self
213 .response
214 .chunk()
215 .await
216 .map_err(|e| BaseError::HttpResponseParseFailed(e.to_string()))?
217 {
218 // 先判后拷,超限时不再多分配一整块 chunk
219 if buf.len() + chunk.len() > limit {
220 return Err(BaseError::HttpResponseTooLarge {
221 limit,
222 actual: None,
223 });
224 }
225 buf.extend_from_slice(&chunk);
226 }
227 Ok(buf)
228 }
229}