Skip to main content

yang_base/http/
client.rs

1//! HTTP 客户端核心实现
2//!
3//! 提供 HTTP 客户端和请求构建能力;实例在启动期经
4//! [`ToolsBuilder::http`](crate::tools::ToolsBuilder) 注册进应用资源,
5//! 运行期通过 `Tools::http()` 或 `ActionContext::http()` 获取。
6
7use crate::error::BaseError;
8use crate::http::request::RequestBuilder;
9use reqwest::{Client, Method};
10use std::sync::{Arc, RwLock};
11use std::time::Duration;
12
13/// 出站响应体默认上限(10 MiB,与出站场景对齐;服务端侧为 DEFAULT_MAX_BODY_BYTES = 2 MiB)
14const DEFAULT_MAX_RESPONSE_BYTES: usize = 10 * 1024 * 1024;
15
16/// HTTP 重定向跟随策略。
17///
18/// 通过 [`HttpClientConfig::redirect`] 配置。默认
19/// `HttpRedirectPolicy::Limited(10)`,与 reqwest 0.12 的默认策略
20/// `reqwest::redirect::Policy::limited(10)` 等价:最多跟随 10 次重定向。
21///
22/// 该策略只控制 client 级重定向跟随行为,**不逐跳校验目标 host,也不会额外
23/// 剥离自定义凭证头**。需要 SSRF 白名单的调用方应显式设为
24/// [`HttpRedirectPolicy::None`],自行检查 3xx 响应的 `Location` 后再发起受控请求。
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26#[non_exhaustive]
27pub enum HttpRedirectPolicy {
28    /// 不跟随任何重定向:3xx 原样返回,`Location` 响应头保留给调用方判断。
29    None,
30    /// 最多跟随 `n` 次重定向;超过上限时 reqwest 返回 `TooManyRedirects` 请求错误。
31    ///
32    /// `Limited(0)` 与 [`HttpRedirectPolicy::None`] 的区别:前者在遇到第一个 3xx 时
33    /// 返回错误,后者把 3xx 响应原样返回。
34    Limited(usize),
35}
36
37impl Default for HttpRedirectPolicy {
38    fn default() -> Self {
39        // 显式对齐 reqwest 0.12.16 的默认策略,而非依赖 reqwest 未来的默认值。
40        Self::Limited(10)
41    }
42}
43
44impl HttpRedirectPolicy {
45    /// 映射为 reqwest 的 client 级重定向策略。
46    fn to_reqwest(self) -> reqwest::redirect::Policy {
47        match self {
48            Self::None => reqwest::redirect::Policy::none(),
49            Self::Limited(max) => reqwest::redirect::Policy::limited(max),
50        }
51    }
52}
53
54/// HTTP 客户端配置
55///
56/// 用于通过 `HttpClient::with_config` 创建自定义配置的客户端
57///
58/// # 示例
59///
60/// ```rust,ignore
61/// use yang_base::http::{HttpClient, HttpClientConfig};
62///
63/// let config = HttpClientConfig {
64///     timeout_secs: 60,
65///     pool_max_idle_per_host: 10,
66///     user_agent: Some("MyApp/1.0".to_string()),
67///     ..Default::default()
68/// };
69/// let client = HttpClient::with_config(config)?;
70/// ```
71#[derive(Debug, Clone)]
72#[non_exhaustive]
73pub struct HttpClientConfig {
74    /// 请求超时时间(秒),默认 30 秒
75    pub timeout_secs: u64,
76
77    /// 每个主机最大空闲连接数,默认 10
78    pub pool_max_idle_per_host: usize,
79
80    /// 连接池空闲超时时间(秒),默认 90 秒
81    pub pool_idle_timeout_secs: u64,
82
83    /// 自定义 User-Agent,默认为 None(使用 reqwest 默认值)
84    pub user_agent: Option<String>,
85
86    /// 是否接受无效的 TLS 证书,默认 false(生产环境不应设为 true)
87    pub accept_invalid_certs: bool,
88
89    /// 代理 URL,默认为 None(不使用代理)
90    pub proxy_url: Option<String>,
91
92    /// 熔断器策略,默认 None(不启用)。设为 `Some(..)` 后,对连续失败的目标
93    /// host 快速失败(返回 `BaseError::HttpCircuitBreakerOpen`),按 host 分键。
94    pub circuit_breaker: Option<crate::http::CircuitBreakerConfig>,
95
96    /// 出站响应体最大允许字节数,默认 10 MiB(`DEFAULT_MAX_RESPONSE_BYTES`)。
97    ///
98    /// 读取响应体(`bytes`/`json`/`text`)时先查 Content-Length 做快速失败,
99    /// 再流式累计校验运行中上限,超限返回 `BaseError::HttpResponseTooLarge`。
100    pub max_response_bytes: usize,
101
102    /// 重定向跟随策略,默认 `HttpRedirectPolicy::Limited(10)`(reqwest 默认:
103    /// 最多跟随 10 跳)。
104    ///
105    /// 默认策略不逐跳校验目标 host,也不会额外剥离自定义凭证头;需要 SSRF
106    /// 白名单或严格同源校验的调用方应显式设为 [`HttpRedirectPolicy::None`],
107    /// 自行校验 3xx 的 `Location`。
108    pub redirect: HttpRedirectPolicy,
109}
110
111impl Default for HttpClientConfig {
112    fn default() -> Self {
113        Self {
114            timeout_secs: 30,
115            pool_max_idle_per_host: 10,
116            pool_idle_timeout_secs: 90,
117            user_agent: None,
118            accept_invalid_certs: false,
119            proxy_url: None,
120            circuit_breaker: None,
121            max_response_bytes: DEFAULT_MAX_RESPONSE_BYTES,
122            redirect: HttpRedirectPolicy::default(),
123        }
124    }
125}
126
127impl HttpClientConfig {
128    /// 验证 HTTP 客户端配置。
129    ///
130    /// 拒绝会导致请求立即失败或连接池配置退化的零值参数。
131    pub fn validate(&self) -> Result<(), BaseError> {
132        if self.timeout_secs == 0 {
133            return Err(BaseError::ParamInvalid(
134                "http.timeout_secs".to_string(),
135                "HTTP 请求超时时间必须大于 0 秒".to_string(),
136            ));
137        }
138        if self.pool_max_idle_per_host == 0 {
139            return Err(BaseError::ParamInvalid(
140                "http.pool_max_idle_per_host".to_string(),
141                "每个主机最大空闲连接数必须大于 0".to_string(),
142            ));
143        }
144        if self.pool_idle_timeout_secs == 0 {
145            return Err(BaseError::ParamInvalid(
146                "http.pool_idle_timeout_secs".to_string(),
147                "连接池空闲超时时间必须大于 0 秒".to_string(),
148            ));
149        }
150        if self.max_response_bytes == 0 {
151            return Err(BaseError::ParamInvalid(
152                "http.max_response_bytes".to_string(),
153                "HTTP 响应体上限必须大于 0 字节".to_string(),
154            ));
155        }
156        if let Some(circuit_breaker) = &self.circuit_breaker {
157            circuit_breaker.validate()?;
158        }
159
160        Ok(())
161    }
162}
163
164#[cfg(test)]
165mod config_tests {
166    use super::*;
167
168    #[test]
169    fn test_http_client_config_validate_rejects_zero_values() {
170        let invalid_configs = [
171            HttpClientConfig {
172                timeout_secs: 0,
173                ..HttpClientConfig::default()
174            },
175            HttpClientConfig {
176                pool_max_idle_per_host: 0,
177                ..HttpClientConfig::default()
178            },
179            HttpClientConfig {
180                pool_idle_timeout_secs: 0,
181                ..HttpClientConfig::default()
182            },
183            HttpClientConfig {
184                max_response_bytes: 0,
185                ..HttpClientConfig::default()
186            },
187        ];
188
189        for config in invalid_configs {
190            let err = config.validate().expect_err("HTTP 客户端零值配置应被拒绝");
191
192            assert!(matches!(err, BaseError::ParamInvalid(_, _)));
193        }
194    }
195
196    #[test]
197    fn test_with_config_rejects_invalid_config_before_building_client() {
198        let config = HttpClientConfig {
199            timeout_secs: 0,
200            ..HttpClientConfig::default()
201        };
202
203        let err = HttpClient::with_config(config)
204            .expect_err("无效 HTTP 配置应在构建 reqwest client 前被拒绝");
205
206        assert!(matches!(err, BaseError::ParamInvalid(field, _) if field == "http.timeout_secs"));
207    }
208
209    #[test]
210    fn test_http_client_config_validate_rejects_invalid_circuit_breaker_config() {
211        let config = HttpClientConfig {
212            circuit_breaker: Some(crate::http::CircuitBreakerConfig {
213                failure_threshold: 0,
214                ..crate::http::CircuitBreakerConfig::default()
215            }),
216            ..HttpClientConfig::default()
217        };
218
219        let err = config
220            .validate()
221            .expect_err("HTTP 客户端应拒绝非法熔断器配置");
222
223        assert!(matches!(
224            err,
225            BaseError::ParamInvalid(field, _) if field == "http.circuit_breaker.failure_threshold"
226        ));
227    }
228
229    #[test]
230    fn test_default_redirect_policy_stays_backward_compatible_and_validates() {
231        // 条件:新增 redirect 配置的 Default 必须等价于 reqwest 0.12.16 的默认
232        // `Policy::limited(10)`,且 validate() 不得新增会拒绝既有合法配置的校验。
233        assert_eq!(
234            HttpClientConfig::default().redirect,
235            HttpRedirectPolicy::Limited(10)
236        );
237        assert_eq!(
238            HttpRedirectPolicy::default(),
239            HttpRedirectPolicy::Limited(10)
240        );
241        assert!(HttpClientConfig::default().validate().is_ok());
242        assert!(HttpClientConfig {
243            redirect: HttpRedirectPolicy::None,
244            ..HttpClientConfig::default()
245        }
246        .validate()
247        .is_ok());
248        assert!(HttpClientConfig {
249            redirect: HttpRedirectPolicy::Limited(0),
250            ..HttpClientConfig::default()
251        }
252        .validate()
253        .is_ok());
254    }
255}
256
257#[cfg(test)]
258mod redirect_policy_tests {
259    use super::*;
260    use tokio::io::{AsyncReadExt, AsyncWriteExt};
261
262    /// 启动一次性 HTTP 服务:读走一个请求后返回固定响应字节。
263    async fn serve_once(response: Vec<u8>) -> std::net::SocketAddr {
264        let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
265            .await
266            .expect("本地监听端口应可绑定");
267        let addr = listener.local_addr().expect("应能取得监听地址");
268
269        tokio::spawn(async move {
270            let Ok((mut stream, _)) = listener.accept().await else {
271                return;
272            };
273            // 读走请求,避免客户端写请求时收到 EPIPE
274            let mut buf = [0u8; 4096];
275            let _ = stream.read(&mut buf).await;
276            let _ = stream.write_all(&response).await;
277            let _ = stream.shutdown().await;
278        });
279
280        addr
281    }
282
283    fn found_response(location: &str) -> Vec<u8> {
284        format!(
285            "HTTP/1.1 302 Found\r\nLocation: {location}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
286        )
287        .into_bytes()
288    }
289
290    fn ok_response(body: &str) -> Vec<u8> {
291        format!(
292            "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
293            body.len()
294        )
295        .into_bytes()
296    }
297
298    /// 回归护栏:默认配置必须保持 reqwest 默认的 `limited(10)`,合法 302 链路
299    /// (同一 127.0.0.1、仅端口不同)仍应自动跟随,行为与修复前一致。
300    #[tokio::test]
301    async fn test_default_redirect_policy_follows_302_as_before() {
302        let target = serve_once(ok_response("ok")).await;
303        let target_url = format!("http://{target}/final");
304        let origin = serve_once(found_response(&target_url)).await;
305
306        let client = HttpClient::new(5).expect("默认客户端应可创建");
307        let response = client
308            .get(&format!("http://{origin}/start"))
309            .send()
310            .await
311            .expect("默认策略下请求应成功");
312
313        assert_eq!(response.status(), 200, "默认策略应跟随 302");
314        assert_eq!(
315            response.url(),
316            target_url,
317            "Response::url() 应返回跟随重定向后的最终 URL"
318        );
319        assert_eq!(
320            response.text().await.expect("应读到最终响应体"),
321            "ok",
322            "默认策略应落到重定向目标"
323        );
324    }
325
326    /// RED(修复前):`HttpClientConfig` 没有 redirect 配置,调用方无法关闭自动
327    /// 跟随,只能被动落到重定向目标,拿不到原始 302 与 Location。
328    #[tokio::test]
329    async fn test_redirect_policy_none_returns_3xx_without_following() {
330        let target = serve_once(ok_response("must-not-be-read")).await;
331        let target_url = format!("http://{target}/final");
332        let origin = serve_once(found_response(&target_url)).await;
333
334        let client = HttpClient::with_config(HttpClientConfig {
335            redirect: HttpRedirectPolicy::None,
336            ..HttpClientConfig::default()
337        })
338        .expect("合法配置应创建客户端");
339
340        let response = client
341            .get(&format!("http://{origin}/start"))
342            .send()
343            .await
344            .expect("None 策略下 3xx 应作为成功响应返回");
345
346        assert_eq!(response.status(), 302, "None 应原样返回 3xx");
347        let location = response
348            .headers()
349            .get(reqwest::header::LOCATION)
350            .and_then(|value| value.to_str().ok())
351            .map(str::to_string);
352        assert_eq!(
353            location.as_deref(),
354            Some(target_url.as_str()),
355            "Location 必须保留给调用方做逐跳校验"
356        );
357    }
358
359    /// `Limited(n)` 必须真正生效:配置 1 跳时,默认的 10 跳策略会跟随的第二跳
360    /// 应触发 reqwest 的 TooManyRedirects 错误。
361    #[tokio::test]
362    async fn test_redirect_policy_limited_stops_after_configured_hops() {
363        let final_server = serve_once(ok_response("too-far")).await;
364        let second_url = format!("http://{final_server}/second");
365        let second = serve_once(found_response(&second_url)).await;
366        let first_url = format!("http://{second}/first");
367        let origin = serve_once(found_response(&first_url)).await;
368
369        let client = HttpClient::with_config(HttpClientConfig {
370            redirect: HttpRedirectPolicy::Limited(1),
371            ..HttpClientConfig::default()
372        })
373        .expect("合法配置应创建客户端");
374
375        // `Response` 未实现 Debug,不能对 `Result<Response, _>` 用 expect_err。
376        let err = match client.get(&format!("http://{origin}/start")).send().await {
377            Ok(_) => panic!("超过跳数上限应返回请求错误"),
378            Err(err) => err,
379        };
380
381        assert!(
382            matches!(&err, BaseError::HttpRequestFailed(_)),
383            "跳数超限应映射为 HttpRequestFailed,实际: {err:?}"
384        );
385    }
386}
387
388/// HTTP 客户端
389///
390/// 提供 HTTP 请求构建和发送能力。
391///
392/// 内部持有 `Arc<reqwest::Client>`,`clone()` 时复用同一连接池(即 `Arc::clone`),
393/// 不会创建新的底层连接池。
394///
395/// # 示例
396///
397/// ```rust,ignore
398/// use yang_base::http::HttpClient;
399/// use yang_base::tools::ToolsBuilder;
400///
401/// // 启动期:把客户端注册进应用资源并冻结
402/// let tools = ToolsBuilder::new().http(HttpClient::new(30)?).build()?;
403///
404/// // 运行期:从 Tools 获取客户端发起请求(Action 内为 ctx.http()?)
405/// let response = tools.http()?
406///     .get("https://api.example.com/users")
407///     .send()
408///     .await?;
409/// ```
410#[derive(Clone, Debug)]
411pub struct HttpClient {
412    /// reqwest 客户端(Arc 包装,clone 时复用同一连接池)
413    client: Client,
414
415    /// 默认超时时间
416    default_timeout: Duration,
417
418    /// 出站响应体最大允许字节数
419    max_response_bytes: usize,
420
421    /// 默认 Token(可选)
422    default_token: Arc<RwLock<Option<String>>>,
423
424    /// 熔断器(可选,默认 None)。clone 时共享同一份状态。
425    circuit_breaker: Option<crate::http::CircuitBreaker>,
426}
427
428impl HttpClient {
429    /// 使用结构化配置创建 HTTP 客户端
430    ///
431    /// # 参数
432    ///
433    /// - `cfg`: HTTP 客户端配置
434    ///
435    /// # 返回
436    ///
437    /// - `Ok(HttpClient)`: 客户端实例
438    /// - `Err(BaseError::HttpClientCreateFailed)`: 创建失败(如代理 URL 无效)
439    ///
440    /// # 示例
441    ///
442    /// ```rust,ignore
443    /// use yang_base::http::{HttpClient, HttpClientConfig};
444    ///
445    /// let config = HttpClientConfig {
446    ///     timeout_secs: 60,
447    ///     pool_max_idle_per_host: 20,
448    ///     ..Default::default()
449    /// };
450    /// let client = HttpClient::with_config(config)?;
451    /// ```
452    pub fn with_config(cfg: HttpClientConfig) -> Result<Self, BaseError> {
453        cfg.validate()?;
454
455        // 安装 rustls 的进程级 CryptoProvider。
456        //
457        // 本 crate 走的是 reqwest 的 `rustls-tls-webpki-roots-no-provider`(原因见
458        // 工作区 `Cargo.toml` 里 reqwest 那段注释:带 provider 的变体会经
459        // `__rustls-ring` 的 `quinn?/ring` 把 quinn 及其 `rand 0.10` 链锁进
460        // `Cargo.lock`,而那条链需要 edition2024,直接击穿 MSRV 1.80)。
461        // `-no-provider` 不替我们选 provider,因此必须在这里显式安装:
462        // 不装的话**第一次 TLS 握手**才会失败("no process-level CryptoProvider
463        // available"),编译期与构造期都看不出来。
464        //
465        // provider 是进程级的,重复安装返回 `Err`,属预期,忽略即可。
466        let _ = rustls::crypto::ring::default_provider().install_default();
467
468        // 构建 reqwest 客户端
469        let mut builder = Client::builder()
470            .timeout(Duration::from_secs(cfg.timeout_secs))
471            .pool_max_idle_per_host(cfg.pool_max_idle_per_host)
472            .pool_idle_timeout(Duration::from_secs(cfg.pool_idle_timeout_secs))
473            .danger_accept_invalid_certs(cfg.accept_invalid_certs);
474
475        // 设置重定向策略:默认显式落到 reqwest 默认的 limited(10),未配置新策略的
476        // 调用方与修复前行为完全一致;重定向仍由 reqwest client 级策略处理。
477        builder = builder.redirect(cfg.redirect.to_reqwest());
478
479        // 设置自定义 User-Agent
480        if let Some(ua) = cfg.user_agent {
481            builder = builder.user_agent(ua);
482        }
483
484        // 设置代理
485        if let Some(proxy_url) = cfg.proxy_url {
486            let proxy =
487                reqwest::Proxy::all(&proxy_url).map_err(BaseError::HttpClientCreateFailed)?;
488            builder = builder.proxy(proxy);
489        }
490
491        let client = builder.build().map_err(BaseError::HttpClientCreateFailed)?;
492
493        let circuit_breaker = cfg
494            .circuit_breaker
495            .map(crate::http::CircuitBreaker::new)
496            .transpose()?;
497
498        Ok(Self {
499            client,
500            default_timeout: Duration::from_secs(cfg.timeout_secs),
501            max_response_bytes: cfg.max_response_bytes,
502            default_token: Arc::new(RwLock::new(None)),
503            circuit_breaker,
504        })
505    }
506
507    /// 创建新的 HTTP 客户端
508    ///
509    /// 委托给 `with_config`,使用默认配置并仅覆盖超时时间。
510    ///
511    /// # 参数
512    ///
513    /// - `timeout_secs`: 默认超时时间(秒)
514    ///
515    /// # 返回
516    ///
517    /// - `Ok(HttpClient)`: 客户端实例
518    /// - `Err(BaseError)`: 创建失败
519    ///
520    /// # 示例
521    ///
522    /// ```rust,ignore
523    /// let client = HttpClient::new(30)?;
524    /// ```
525    pub fn new(timeout_secs: u64) -> Result<Self, BaseError> {
526        // 委托给 with_config,仅覆盖超时时间
527        Self::with_config(HttpClientConfig {
528            timeout_secs,
529            ..Default::default()
530        })
531    }
532
533    /// 设置默认 Token
534    ///
535    /// # 参数
536    ///
537    /// - `token`: Token 字符串
538    ///
539    /// # 示例
540    ///
541    /// ```rust,ignore
542    /// let mut client = HttpClient::new(30)?;
543    /// client.set_default_token("your_token".to_string());
544    /// ```
545    pub fn set_default_token(&self, token: String) {
546        // 使用 unwrap_or_else 处理锁中毒:即使锁中毒也能恢复数据并继续写入
547        let mut default_token = self
548            .default_token
549            .write()
550            .unwrap_or_else(|p| p.into_inner());
551        *default_token = Some(token);
552        log::debug!("已设置默认 Token");
553    }
554
555    /// 获取默认 Token
556    fn get_default_token(&self) -> Option<String> {
557        // 使用 unwrap_or_else 处理锁中毒:即使锁中毒也能恢复数据并继续读取
558        let default_token = self.default_token.read().unwrap_or_else(|p| p.into_inner());
559        default_token.clone()
560    }
561
562    /// 创建请求构建器
563    ///
564    /// 注意:`self.client.clone()` 是 `Arc::clone`,复用同一底层连接池,
565    /// 不会创建新的 TCP 连接池,多个请求共享连接。
566    ///
567    /// # 参数
568    ///
569    /// - `method`: HTTP 方法
570    /// - `url`: 请求 URL
571    ///
572    /// # 返回
573    ///
574    /// - `RequestBuilder`: 请求构建器
575    ///
576    /// # 示例
577    ///
578    /// ```rust,ignore
579    /// use reqwest::Method;
580    ///
581    /// let response = client
582    ///     .request(Method::GET, "https://api.example.com/users")
583    ///     .send()
584    ///     .await?;
585    /// ```
586    pub fn request(&self, method: Method, url: &str) -> RequestBuilder {
587        // self.client.clone() 是 Arc::clone,复用同一连接池
588        RequestBuilder::new(
589            self.client.clone(),
590            method,
591            url.to_string(),
592            self.default_timeout,
593            self.max_response_bytes,
594            self.get_default_token(),
595            self.circuit_breaker.clone(),
596        )
597    }
598
599    /// GET 请求
600    ///
601    /// # 参数
602    ///
603    /// - `url`: 请求 URL
604    ///
605    /// # 返回
606    ///
607    /// - `RequestBuilder`: 请求构建器
608    ///
609    /// # 示例
610    ///
611    /// ```rust,ignore
612    /// let response = client
613    ///     .get("https://api.example.com/users")
614    ///     .send()
615    ///     .await?;
616    /// ```
617    pub fn get(&self, url: &str) -> RequestBuilder {
618        self.request(Method::GET, url)
619    }
620
621    /// POST 请求
622    ///
623    /// # 参数
624    ///
625    /// - `url`: 请求 URL
626    ///
627    /// # 返回
628    ///
629    /// - `RequestBuilder`: 请求构建器
630    ///
631    /// # 示例
632    ///
633    /// ```rust,ignore
634    /// let response = client
635    ///     .post("https://api.example.com/users")
636    ///     .json(&user)?
637    ///     .send()
638    ///     .await?;
639    /// ```
640    pub fn post(&self, url: &str) -> RequestBuilder {
641        self.request(Method::POST, url)
642    }
643
644    /// PUT 请求
645    ///
646    /// # 参数
647    ///
648    /// - `url`: 请求 URL
649    ///
650    /// # 返回
651    ///
652    /// - `RequestBuilder`: 请求构建器
653    ///
654    /// # 示例
655    ///
656    /// ```rust,ignore
657    /// let response = client
658    ///     .put("https://api.example.com/users/1")
659    ///     .json(&user)?
660    ///     .send()
661    ///     .await?;
662    /// ```
663    pub fn put(&self, url: &str) -> RequestBuilder {
664        self.request(Method::PUT, url)
665    }
666
667    /// DELETE 请求
668    ///
669    /// # 参数
670    ///
671    /// - `url`: 请求 URL
672    ///
673    /// # 返回
674    ///
675    /// - `RequestBuilder`: 请求构建器
676    ///
677    /// # 示例
678    ///
679    /// ```rust,ignore
680    /// let response = client
681    ///     .delete("https://api.example.com/users/1")
682    ///     .send()
683    ///     .await?;
684    /// ```
685    pub fn delete(&self, url: &str) -> RequestBuilder {
686        self.request(Method::DELETE, url)
687    }
688
689    /// PATCH 请求
690    ///
691    /// # 参数
692    ///
693    /// - `url`: 请求 URL
694    ///
695    /// # 返回
696    ///
697    /// - `RequestBuilder`: 请求构建器
698    ///
699    /// # 示例
700    ///
701    /// ```rust,ignore
702    /// let response = client
703    ///     .patch("https://api.example.com/users/1")
704    ///     .json(&updates)?
705    ///     .send()
706    ///     .await?;
707    /// ```
708    pub fn patch(&self, url: &str) -> RequestBuilder {
709        self.request(Method::PATCH, url)
710    }
711}