boluo/data.rs
1//! 通用数据类型。
2
3use std::ops::{Deref, DerefMut};
4
5/// JSON 提取器和响应。
6///
7/// # 提取
8///
9/// 当用作提取器时,[`Json`] 可以将请求体反序列化为实现 [`serde::de::DeserializeOwned`] 的类型。
10///
11/// ```
12/// use boluo::data::Json;
13///
14/// #[derive(serde::Deserialize)]
15/// struct CreateUser {
16/// username: String,
17/// password: String,
18/// }
19///
20/// #[boluo::route("/users", method = "POST")]
21/// async fn create_user(Json(user): Json<CreateUser>) {
22/// // 创建用户。
23/// }
24/// ```
25///
26/// # 响应
27///
28/// 当用作响应时,[`Json`] 可以将实现 [`serde::Serialize`] 的类型序列化为 JSON,
29/// 并设置响应标头 `Content-Type: application/json`。
30///
31/// ```
32/// use boluo::data::Json;
33/// use boluo::extract::Path;
34///
35/// #[derive(serde::Serialize)]
36/// struct User {
37/// id: String,
38/// username: String,
39/// }
40///
41/// #[boluo::route("/users/{id}", method = "GET")]
42/// async fn get_user(Path(id): Path<String>) -> Json<User> {
43/// let user = find_user(&id).await;
44/// Json(user)
45/// }
46///
47/// async fn find_user(id: &str) -> User {
48/// todo!()
49/// }
50/// ```
51#[derive(Debug, Clone, Copy)]
52pub struct Json<T>(pub T);
53
54impl<T> Deref for Json<T> {
55 type Target = T;
56
57 #[inline]
58 fn deref(&self) -> &Self::Target {
59 &self.0
60 }
61}
62
63impl<T> DerefMut for Json<T> {
64 #[inline]
65 fn deref_mut(&mut self) -> &mut Self::Target {
66 &mut self.0
67 }
68}
69
70impl<T> Json<T> {
71 /// 得到内部的值。
72 #[inline]
73 pub fn into_inner(this: Self) -> T {
74 this.0
75 }
76}
77
78/// 表单提取器和响应。
79///
80/// # 提取
81///
82/// 当用作提取器时,[`Form`] 可以将请求中的表单数据反序列化为实现
83/// [`serde::de::DeserializeOwned`] 的类型。
84///
85/// 如果请求具有 `GET` 或 `HEAD` 方法,则会从查询字符串中读取表单数据(与 [`Query`] 相同),
86/// 如果请求具有不同的方法,则会从请求体中读取表单数据。
87///
88/// ```
89/// use boluo::data::Form;
90///
91/// #[derive(serde::Deserialize)]
92/// struct CreateUser {
93/// username: String,
94/// password: String,
95/// }
96///
97/// #[boluo::route("/users", method = "POST")]
98/// async fn create_user(Form(user): Form<CreateUser>) {
99/// // 创建用户。
100/// }
101/// ```
102///
103/// # 响应
104///
105/// 当用作响应时,[`Form`] 可以将实现 [`serde::Serialize`] 的类型序列化为表单,
106/// 并设置响应标头 `Content-Type: application/x-www-form-urlencoded`。
107///
108/// ```
109/// use boluo::data::Form;
110/// use boluo::extract::Path;
111///
112/// #[derive(serde::Serialize)]
113/// struct User {
114/// id: String,
115/// username: String,
116/// }
117///
118/// #[boluo::route("/users/{id}", method = "GET")]
119/// async fn get_user(Path(id): Path<String>) -> Form<User> {
120/// let user = find_user(&id).await;
121/// Form(user)
122/// }
123///
124/// async fn find_user(id: &str) -> User {
125/// todo!()
126/// }
127/// ```
128///
129/// [`Query`]: crate::extract::Query
130#[derive(Debug, Clone, Copy)]
131pub struct Form<T>(pub T);
132
133impl<T> Deref for Form<T> {
134 type Target = T;
135
136 #[inline]
137 fn deref(&self) -> &Self::Target {
138 &self.0
139 }
140}
141
142impl<T> DerefMut for Form<T> {
143 #[inline]
144 fn deref_mut(&mut self) -> &mut Self::Target {
145 &mut self.0
146 }
147}
148
149impl<T> Form<T> {
150 /// 得到内部的值。
151 #[inline]
152 pub fn into_inner(this: Self) -> T {
153 this.0
154 }
155}
156
157/// 扩展提取器和响应。
158///
159/// # 提取
160///
161/// 这通常用于在处理程序之间共享状态。
162///
163/// ```
164/// use std::sync::Arc;
165///
166/// use boluo::data::Extension;
167/// use boluo::route::Router;
168/// use boluo::service::ServiceExt;
169///
170/// // 在整个应用程序中使用的一些共享状态。
171/// struct State {
172/// // ...
173/// }
174///
175/// #[boluo::route("/")]
176/// async fn handler(Extension(state): Extension<Arc<State>>) {
177/// // ...
178/// }
179///
180/// let state = Arc::new(State { /* ... */ });
181///
182/// Router::new().mount(handler)
183/// // 添加中间件,将状态插入到所有传入请求的扩展中。
184/// .with(Extension(state));
185/// ```
186///
187/// # 响应
188///
189/// 响应扩展可以用于与中间件共享状态。
190///
191/// ```
192/// use boluo::data::Extension;
193/// use boluo::response::IntoResponse;
194///
195/// #[derive(Clone)]
196/// struct Foo(&'static str);
197///
198/// async fn handler() -> impl IntoResponse {
199/// (Extension(Foo("foo")), "Hello, World!")
200/// }
201/// ```
202#[derive(Debug, Clone, Copy)]
203pub struct Extension<T>(pub T);
204
205impl<T> Deref for Extension<T> {
206 type Target = T;
207
208 #[inline]
209 fn deref(&self) -> &Self::Target {
210 &self.0
211 }
212}
213
214impl<T> DerefMut for Extension<T> {
215 #[inline]
216 fn deref_mut(&mut self) -> &mut Self::Target {
217 &mut self.0
218 }
219}
220
221impl<T> Extension<T> {
222 /// 得到内部的值。
223 #[inline]
224 pub fn into_inner(this: Self) -> T {
225 this.0
226 }
227}