unistore_http/
facade.rs

1//! HTTP 便捷函数门面
2//!
3//! 职责:
4//! - 提供全局默认客户端
5//! - 提供一行代码完成请求的便捷函数
6//! - Level 3 API:最简单的使用方式
7
8use super::client::HttpClient;
9use super::error::HttpError;
10use super::response::Response;
11use serde::de::DeserializeOwned;
12use serde::Serialize;
13use std::sync::OnceLock;
14
15/// 全局默认客户端(惰性初始化)
16static DEFAULT_CLIENT: OnceLock<HttpClient> = OnceLock::new();
17
18/// 获取或初始化全局默认客户端
19///
20/// 首次调用时初始化,后续调用返回同一实例
21fn default_client() -> Result<&'static HttpClient, HttpError> {
22    if DEFAULT_CLIENT.get().is_none() {
23        let client = HttpClient::new()?;
24        // 忽略重复初始化的结果(可能有并发初始化)
25        let _ = DEFAULT_CLIENT.set(client);
26    }
27
28    DEFAULT_CLIENT.get().ok_or(HttpError::Other("客户端初始化失败".to_string()))
29}
30
31/// 快捷 GET 请求
32///
33/// # Example
34///
35/// ```ignore
36/// use unistore_http::get;
37///
38/// let response = get("https://api.example.com/status").await?;
39/// let body = response.text()?;
40/// ```
41pub async fn get(url: &str) -> Result<Response, HttpError> {
42    default_client()?.get(url).await
43}
44
45/// 快捷 GET 请求并解析为 JSON
46///
47/// # Example
48///
49/// ```ignore
50/// use unistore_http::get_json;
51///
52/// #[derive(Deserialize)]
53/// struct User {
54///     name: String,
55///     email: String,
56/// }
57///
58/// let user: User = get_json("https://api.example.com/user/1").await?;
59/// ```
60pub async fn get_json<T: DeserializeOwned>(url: &str) -> Result<T, HttpError> {
61    default_client()?.get(url).await?.into_json()
62}
63
64/// 快捷 GET 请求并获取文本
65///
66/// # Example
67///
68/// ```ignore
69/// let html = get_text("https://example.com").await?;
70/// ```
71pub async fn get_text(url: &str) -> Result<String, HttpError> {
72    default_client()?.get(url).await?.into_text()
73}
74
75/// 快捷 GET 请求并获取字节
76///
77/// # Example
78///
79/// ```ignore
80/// let bytes = get_bytes("https://example.com/image.png").await?;
81/// ```
82pub async fn get_bytes(url: &str) -> Result<Vec<u8>, HttpError> {
83    Ok(default_client()?.get(url).await?.into_bytes())
84}
85
86/// 快捷 POST 请求(JSON body)
87///
88/// # Example
89///
90/// ```ignore
91/// use unistore_http::post_json;
92///
93/// #[derive(Serialize)]
94/// struct CreateUser {
95///     name: String,
96///     email: String,
97/// }
98///
99/// let user = CreateUser {
100///     name: "Alice".into(),
101///     email: "alice@example.com".into(),
102/// };
103///
104/// let response = post_json("https://api.example.com/users", &user).await?;
105/// ```
106pub async fn post_json<T: Serialize>(url: &str, body: &T) -> Result<Response, HttpError> {
107    default_client()?.post_json(url, body).await
108}
109
110/// 快捷 POST 请求(JSON body)并解析响应为 JSON
111///
112/// # Example
113///
114/// ```ignore
115/// let created_user: User = post_json_for_json(
116///     "https://api.example.com/users",
117///     &new_user
118/// ).await?;
119/// ```
120pub async fn post_json_for_json<T: Serialize, R: DeserializeOwned>(
121    url: &str,
122    body: &T,
123) -> Result<R, HttpError> {
124    default_client()?.post_json(url, body).await?.into_json()
125}
126
127/// 快捷 POST 请求(表单 body)
128///
129/// # Example
130///
131/// ```ignore
132/// use unistore_http::post_form;
133///
134/// #[derive(Serialize)]
135/// struct LoginForm {
136///     username: String,
137///     password: String,
138/// }
139///
140/// let form = LoginForm {
141///     username: "alice".into(),
142///     password: "secret".into(),
143/// };
144///
145/// let response = post_form("https://example.com/login", &form).await?;
146/// ```
147pub async fn post_form<T: Serialize>(url: &str, body: &T) -> Result<Response, HttpError> {
148    default_client()?.post_form(url, body).await
149}
150
151/// 快捷 PUT 请求(JSON body)
152///
153/// # Example
154///
155/// ```ignore
156/// let response = put_json(
157///     "https://api.example.com/users/1",
158///     &updated_user
159/// ).await?;
160/// ```
161pub async fn put_json<T: Serialize>(url: &str, body: &T) -> Result<Response, HttpError> {
162    default_client()?.put_json(url, body).await
163}
164
165/// 快捷 DELETE 请求
166///
167/// # Example
168///
169/// ```ignore
170/// let response = delete("https://api.example.com/users/1").await?;
171/// ```
172pub async fn delete(url: &str) -> Result<Response, HttpError> {
173    default_client()?.delete(url).await
174}
175
176/// 快捷 PATCH 请求(JSON body)
177///
178/// # Example
179///
180/// ```ignore
181/// let response = patch_json(
182///     "https://api.example.com/users/1",
183///     &partial_update
184/// ).await?;
185/// ```
186pub async fn patch_json<T: Serialize>(url: &str, body: &T) -> Result<Response, HttpError> {
187    default_client()?.patch_json(url, body).await
188}
189
190/// 快捷 HEAD 请求
191///
192/// # Example
193///
194/// ```ignore
195/// let response = head("https://example.com/file.zip").await?;
196/// let size = response.content_length();
197/// ```
198pub async fn head(url: &str) -> Result<Response, HttpError> {
199    default_client()?.head(url).await
200}
201
202#[cfg(test)]
203mod tests {
204    // 便捷函数的测试需要网络,放在集成测试中
205}