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 /// 获取响应体为文本
105 ///
106 /// # 返回
107 ///
108 /// - `Ok(String)`: 响应文本
109 /// - `Err(BaseError)`: 解析失败
110 ///
111 /// # 示例
112 ///
113 /// ```rust,ignore
114 /// let text = response.text().await?;
115 /// println!("响应内容: {}", text);
116 /// ```
117 pub async fn text(self) -> Result<String, BaseError> {
118 // 必须在 read_body_limited() 消耗 self 之前取出 charset,保留现 charset feature 语义。
119 let charset = self
120 .response
121 .headers()
122 .get(reqwest::header::CONTENT_TYPE)
123 .and_then(|v| v.to_str().ok())
124 .and_then(|v| v.split(';').find_map(|p| p.trim().strip_prefix("charset=")))
125 .and_then(|label| encoding_rs::Encoding::for_label(label.trim().as_bytes()))
126 .unwrap_or(encoding_rs::UTF_8);
127 let body = self.read_body_limited().await?;
128 let (text, _, _) = charset.decode(&body);
129 Ok(text.into_owned())
130 }
131
132 /// 获取响应体为字节流
133 ///
134 /// # 返回
135 ///
136 /// - `Ok(Vec<u8>)`: 响应字节
137 /// - `Err(BaseError)`: 解析失败
138 ///
139 /// # 示例
140 ///
141 /// ```rust,ignore
142 /// let bytes = response.bytes().await?;
143 /// println!("响应大小: {} 字节", bytes.len());
144 /// ```
145 pub async fn bytes(self) -> Result<Vec<u8>, BaseError> {
146 self.read_body_limited().await
147 }
148
149 /// 获取响应体为 JSON
150 ///
151 /// # 类型参数
152 ///
153 /// - `T`: 目标类型,必须实现 `serde::de::DeserializeOwned`
154 ///
155 /// # 返回
156 ///
157 /// - `Ok(T)`: 反序列化后的对象
158 /// - `Err(BaseError)`: 解析失败
159 ///
160 /// # 示例
161 ///
162 /// ```rust,ignore
163 /// #[derive(Deserialize)]
164 /// struct User {
165 /// id: u64,
166 /// name: String,
167 /// }
168 ///
169 /// let user: User = response.json().await?;
170 /// println!("用户: {} (ID: {})", user.name, user.id);
171 /// ```
172 pub async fn json<T: serde::de::DeserializeOwned>(self) -> Result<T, BaseError> {
173 let body = self.read_body_limited().await?;
174 serde_json::from_slice(&body).map_err(|e| BaseError::JsonDeserializeFailed(e.to_string()))
175 }
176
177 /// 按上限流式读取响应体。
178 ///
179 /// 上游可能省略(chunked)或谎报 Content-Length,因此头部预检只做快速失败,
180 /// 真正的硬上限由下面的运行中累计校验保证(验证需求: M12)。
181 async fn read_body_limited(mut self) -> Result<Vec<u8>, BaseError> {
182 let limit = self.max_response_bytes;
183 if let Some(len) = self.response.content_length() {
184 if len > limit as u64 {
185 return Err(BaseError::HttpResponseTooLarge {
186 limit,
187 actual: Some(len),
188 });
189 }
190 }
191 let mut buf: Vec<u8> = Vec::with_capacity(limit.min(64 * 1024));
192 while let Some(chunk) = self
193 .response
194 .chunk()
195 .await
196 .map_err(|e| BaseError::HttpResponseParseFailed(e.to_string()))?
197 {
198 // 先判后拷,超限时不再多分配一整块 chunk
199 if buf.len() + chunk.len() > limit {
200 return Err(BaseError::HttpResponseTooLarge {
201 limit,
202 actual: None,
203 });
204 }
205 buf.extend_from_slice(&chunk);
206 }
207 Ok(buf)
208 }
209}