Skip to main content

wx_rust_common/util/http/
simple_get_request_executor.rs

1//! 简单 GET 请求执行器。
2//!
3//! 对应 Java `me.chanjar.weixin.common.util.http.SimpleGetRequestExecutor`。
4//! Java 提供 apache/okhttp/jodd/httpcomponents 四后端;Rust 以 reqwest 统一实现。
5
6use async_trait::async_trait;
7
8use crate::enums::WxType;
9use crate::error::{WxError, WxErrorError, WxErrorException};
10use crate::util::http::{RequestExecutor, ResponseHandler};
11
12/// 简单的 GET 请求执行器。
13///
14/// 请求参数是 `String`(query 串),返回结果也是 `String`。
15/// 请求前自动校验微信错误码(`errcode != 0` 抛异常)。
16#[derive(Debug, Clone)]
17pub struct SimpleGetRequestExecutor {
18    /// reqwest 客户端
19    client: reqwest::Client,
20}
21
22impl SimpleGetRequestExecutor {
23    /// 构建 GET 执行器。
24    ///
25    /// # 参数
26    /// - `client`:reqwest 客户端
27    pub fn new(client: reqwest::Client) -> Self {
28        Self { client }
29    }
30
31    /// 通用响应校验:从响应内容解析 `WxError`,错误码非 0 时抛异常。
32    ///
33    /// # 参数
34    /// - `wx_type`:微信模块类型(用于错误码翻译)
35    /// - `response_content`:响应内容
36    ///
37    /// # 返回
38    /// 原始响应内容;错误码非 0 时返回错误。
39    pub fn handle_response(
40        wx_type: WxType,
41        response_content: &str,
42    ) -> Result<String, WxErrorException> {
43        let error = WxError::from_json_with_type(response_content, Some(wx_type));
44        if error.error_code != 0 {
45            // 保留完整 `WxError`(含原始报文 `json`),供上层从错误报文回解析业务数据
46            // (对应 Java `SimpleGetRequestExecutor.handleResponse` 抛出的
47            // `new WxErrorException(error)`;如 miniapp `createRoom` 对 300036
48            // 从 `error.getJson()` 回解析 roomId)。
49            return Err(WxErrorException::Wx(WxErrorError::new(error)));
50        }
51        Ok(response_content.to_string())
52    }
53}
54
55#[async_trait]
56impl RequestExecutor<String, String> for SimpleGetRequestExecutor {
57    async fn execute(
58        &self,
59        uri: &str,
60        data: String,
61        wx_type: WxType,
62    ) -> Result<String, WxErrorException> {
63        // data 为 query 参数串(如 "a=1&b=2"),拼接到 uri
64        let url = if data.is_empty() {
65            uri.to_string()
66        } else if uri.contains('?') {
67            format!("{uri}&{data}")
68        } else {
69            format!("{uri}?{data}")
70        };
71        let resp = self.client.get(&url).send().await?;
72        let body = resp.text().await?;
73        Self::handle_response(wx_type, &body)
74    }
75}
76
77#[async_trait]
78impl ResponseHandler<String> for SimpleGetRequestExecutor {
79    async fn handle(&self, response: String) {
80        let _ = response;
81    }
82}