silent 2.16.1

Silent Web Framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
use async_trait::async_trait;

use crate::core::path_param::PathParam as CorePathParam;
use crate::{Request, Response, SilentError, headers::HeaderMapExt};

#[allow(deprecated)]
use super::types::Configs;
use super::types::{
    Extension, Form, Json, Method, Path, Query, RemoteAddr, State, TypedHeader, Uri, Version,
};

/// `FromRequest` 是萃取器的核心 trait,用于从 HTTP 请求中提取特定类型的数据。
///
/// 通过实现这个 trait,您可以创建自定义的萃取器,从请求中提取任何需要的数据。
/// 所有内置萃取器(Path、Query、Json 等)都实现了这个 trait。
///
/// ## 基本用法
///
/// 要实现一个自定义萃取器,您需要:
/// 1. 定义您的数据类型
/// 2. 实现 `FromRequest` trait
/// 3. 在处理函数中使用萃取器
///
/// ## 示例:创建 JWT 令牌萃取器
///
/// ```rust
/// use async_trait::async_trait;
/// use silent::extractor::FromRequest;
/// use silent::{Request, Result, SilentError};
///
/// struct JwtToken(String);
///
/// #[async_trait]
/// impl FromRequest for JwtToken {
///     type Rejection = SilentError;
///
///     async fn from_request(req: &mut Request) -> std::result::Result<Self, Self::Rejection> {
///         let token = req.headers()
///             .get("authorization")
///             .and_then(|v| v.to_str().ok())
///             .and_then(|s| s.strip_prefix("Bearer "))
///             .map(|s| s.to_string())
///             .ok_or(SilentError::ParamsNotFound)?;
///
///         Ok(JwtToken(token))
///     }
/// }
///
/// // 使用自定义萃取器
/// async fn protected_handler(token: JwtToken) -> Result<String> {
///     Ok(format!("访问受保护的资源,Token: {}", token.0))
/// }
/// ```
///
/// ## 错误处理
///
/// `FromRequest` 的 `Rejection` 类型决定了萃取失败时的错误类型。常用的错误类型:
/// - `SilentError`:框架内置错误,包含 `ParamsNotFound`、`ParamsEmpty` 等
/// - `Response`:直接返回 HTTP 响应
///
/// ## 组合使用
///
/// 多个萃取器可以组合使用:
///
/// ```rust
/// use silent::Result;
/// use silent::extractor::{Path, Query, Json};
/// use serde::Deserialize;
///
/// #[derive(Deserialize)]
/// struct Page {
///     page: u32,
///     size: u32,
/// }
///
/// #[derive(Deserialize)]
/// struct Data {
///     name: String,
/// }
///
/// async fn handler(
///     (Path(id), Query(p), Json(data)): (Path<i64>, Query<Page>, Json<Data>),
/// ) -> Result<String> {
///     // 处理提取的数据
///     Ok("成功".to_string())
/// }
/// ```
///
/// ## 可选参数
///
/// 使用 `Option<T>` 可以处理可选参数:
///
/// ```rust
/// use silent::Result;
/// use silent::extractor::Path;
///
/// async fn handler(opt_id: Option<Path<i64>>) -> Result<String> {
///     match opt_id {
///         Some(Path(id)) => Ok(format!("ID: {}", id)),
///         None => Ok("无ID".to_string()),
///     }
/// }
/// ```
#[async_trait]
pub trait FromRequest: Sized {
    /// 萃取失败时的错误类型
    ///
    /// 这个类型必须能够转换为 HTTP 响应(实现了 `Into<Response>`)
    type Rejection: Into<crate::Response> + Send + 'static;

    /// 从请求中提取数据
    ///
    /// # 参数
    ///
    /// * `req` - 可变的请求引用,可以从中提取数据
    ///
    /// # 返回值
    ///
    /// 返回 `Result<Self, Self::Rejection>`:
    /// - 成功时返回 `Ok(extracted_value)`
    /// - 失败时返回 `Err(error)`
    ///
    /// # 示例
    ///
    /// 参见上面 `FromRequest` trait 的完整示例。
    async fn from_request(req: &mut Request) -> Result<Self, Self::Rejection>;
}

#[async_trait]
impl<T> FromRequest for Path<T>
where
    for<'de> T: serde::Deserialize<'de> + Send + 'static,
{
    type Rejection = SilentError;

    async fn from_request(req: &mut Request) -> Result<Self, Self::Rejection> {
        use crate::core::serde::{from_str_map, from_str_val};
        let params = req.path_params();
        if params.is_empty() {
            return Err(SilentError::ParamsEmpty);
        }

        if params.len() == 1 {
            let value = params.values().next().unwrap();
            let single = path_param_to_string(value);
            let parsed: T = from_str_val(single.as_str())?;
            return Ok(Path(parsed));
        }

        let map_iter = params
            .iter()
            .map(|(k, v)| (k.as_str(), path_param_to_string(v)));
        let parsed: T = from_str_map(map_iter)?;
        Ok(Path(parsed))
    }
}

#[async_trait]
impl<T> FromRequest for Query<T>
where
    for<'de> T: serde::Deserialize<'de> + Send + 'static,
{
    type Rejection = SilentError;

    async fn from_request(req: &mut Request) -> Result<Self, Self::Rejection> {
        let value = req.params_parse::<T>()?;
        Ok(Query(value))
    }
}

#[async_trait]
impl<T> FromRequest for Json<T>
where
    for<'de> T: serde::Deserialize<'de> + Send + 'static,
{
    type Rejection = SilentError;

    async fn from_request(req: &mut Request) -> Result<Self, Self::Rejection> {
        let value = req.json_parse::<T>().await?;
        Ok(Json(value))
    }
}

#[async_trait]
impl<T> FromRequest for Form<T>
where
    for<'de> T: serde::Deserialize<'de> + serde::Serialize + Send + 'static,
{
    type Rejection = SilentError;

    async fn from_request(req: &mut Request) -> Result<Self, Self::Rejection> {
        let value = req.form_parse::<T>().await?;
        Ok(Form(value))
    }
}

#[async_trait]
impl<T> FromRequest for State<T>
where
    T: Send + Sync + Clone + 'static,
{
    type Rejection = SilentError;

    async fn from_request(req: &mut Request) -> Result<Self, Self::Rejection> {
        let val = req.get_state::<T>()?.clone();
        Ok(State(val))
    }
}

#[allow(deprecated)]
#[async_trait]
impl<T> FromRequest for Configs<T>
where
    T: Send + Sync + Clone + 'static,
{
    type Rejection = SilentError;

    async fn from_request(req: &mut Request) -> Result<Self, Self::Rejection> {
        let cfg = req.get_state::<T>()?.clone();
        Ok(Configs(cfg))
    }
}

#[async_trait]
impl<T> FromRequest for Extension<T>
where
    T: Clone + Send + Sync + 'static,
{
    type Rejection = SilentError;

    async fn from_request(req: &mut Request) -> Result<Self, Self::Rejection> {
        let ext = req
            .extensions()
            .get::<T>()
            .cloned()
            .ok_or(SilentError::ParamsNotFound)?;
        Ok(Extension(ext))
    }
}

#[async_trait]
impl<H> FromRequest for TypedHeader<H>
where
    H: headers::Header + Send + 'static,
{
    type Rejection = SilentError;

    async fn from_request(req: &mut Request) -> Result<Self, Self::Rejection> {
        let h = req
            .headers()
            .typed_get::<H>()
            .ok_or(SilentError::ParamsNotFound)?;
        Ok(TypedHeader(h))
    }
}

#[async_trait]
impl FromRequest for Method {
    type Rejection = SilentError;
    async fn from_request(req: &mut Request) -> Result<Self, Self::Rejection> {
        Ok(Method(req.method().clone()))
    }
}

#[async_trait]
impl FromRequest for Uri {
    type Rejection = SilentError;
    async fn from_request(req: &mut Request) -> Result<Self, Self::Rejection> {
        Ok(Uri(req.uri().clone()))
    }
}

#[async_trait]
impl FromRequest for Version {
    type Rejection = SilentError;
    async fn from_request(req: &mut Request) -> Result<Self, Self::Rejection> {
        Ok(Version(req.version()))
    }
}

#[async_trait]
impl FromRequest for RemoteAddr {
    type Rejection = SilentError;
    async fn from_request(req: &mut Request) -> Result<Self, Self::Rejection> {
        Ok(RemoteAddr(req.remote()))
    }
}

#[async_trait]
impl<A> FromRequest for (A,)
where
    A: FromRequest + Send + 'static,
{
    type Rejection = Response;

    async fn from_request(req: &mut Request) -> Result<Self, Self::Rejection> {
        let a = match <A as FromRequest>::from_request(req).await {
            Ok(v) => v,
            Err(e) => return Err(e.into()),
        };
        Ok((a,))
    }
}

#[async_trait]
impl<A, B> FromRequest for (A, B)
where
    A: FromRequest + Send + 'static,
    B: FromRequest + Send + 'static,
{
    type Rejection = Response;

    async fn from_request(req: &mut Request) -> Result<Self, Self::Rejection> {
        let a = match <A as FromRequest>::from_request(req).await {
            Ok(v) => v,
            Err(e) => return Err(e.into()),
        };
        let b = match <B as FromRequest>::from_request(req).await {
            Ok(v) => v,
            Err(e) => return Err(e.into()),
        };
        Ok((a, b))
    }
}

#[async_trait]
impl<A, B, C> FromRequest for (A, B, C)
where
    A: FromRequest + Send + 'static,
    B: FromRequest + Send + 'static,
    C: FromRequest + Send + 'static,
{
    type Rejection = Response;

    async fn from_request(req: &mut Request) -> Result<Self, Self::Rejection> {
        let a = match <A as FromRequest>::from_request(req).await {
            Ok(v) => v,
            Err(e) => return Err(e.into()),
        };
        let b = match <B as FromRequest>::from_request(req).await {
            Ok(v) => v,
            Err(e) => return Err(e.into()),
        };
        let c = match <C as FromRequest>::from_request(req).await {
            Ok(v) => v,
            Err(e) => return Err(e.into()),
        };
        Ok((a, b, c))
    }
}

#[async_trait]
impl<A, B, C, D> FromRequest for (A, B, C, D)
where
    A: FromRequest + Send + 'static,
    B: FromRequest + Send + 'static,
    C: FromRequest + Send + 'static,
    D: FromRequest + Send + 'static,
{
    type Rejection = Response;

    async fn from_request(req: &mut Request) -> Result<Self, Self::Rejection> {
        let a = match <A as FromRequest>::from_request(req).await {
            Ok(v) => v,
            Err(e) => return Err(e.into()),
        };
        let b = match <B as FromRequest>::from_request(req).await {
            Ok(v) => v,
            Err(e) => return Err(e.into()),
        };
        let c = match <C as FromRequest>::from_request(req).await {
            Ok(v) => v,
            Err(e) => return Err(e.into()),
        };
        let d = match <D as FromRequest>::from_request(req).await {
            Ok(v) => v,
            Err(e) => return Err(e.into()),
        };
        Ok((a, b, c, d))
    }
}

#[async_trait]
impl<T> FromRequest for Option<T>
where
    T: FromRequest + Send + 'static,
{
    type Rejection = Response;

    async fn from_request(req: &mut Request) -> Result<Self, Self::Rejection> {
        match T::from_request(req).await {
            Ok(v) => Ok(Some(v)),
            Err(_e) => Ok(None),
        }
    }
}

#[async_trait]
impl<T> FromRequest for Result<T, Response>
where
    T: FromRequest + Send + 'static,
{
    type Rejection = Response;

    async fn from_request(req: &mut Request) -> Result<Self, Self::Rejection> {
        match T::from_request(req).await {
            Ok(v) => Ok(Ok(v)),
            Err(e) => Ok(Err(e.into())),
        }
    }
}

#[inline]
fn path_param_to_string(param: &CorePathParam) -> String {
    match param {
        CorePathParam::Str(s) | CorePathParam::Path(s) => s.as_str().to_string(),
        CorePathParam::Int(v) => v.to_string(),
        CorePathParam::Int32(v) => v.to_string(),
        CorePathParam::Int64(v) => v.to_string(),
        CorePathParam::UInt32(v) => v.to_string(),
        CorePathParam::UInt64(v) => v.to_string(),
        CorePathParam::Uuid(u) => u.to_string(),
    }
}