rupring/
request.rs

1/*!
2# About Request
3- You can access any value provided in an HTTP Request through the Request parameter.
4
5```rust
6#[rupring::Get(path = /:id)]
7pub fn hello(request: rupring::Request) -> rupring::Response {
8    let method = request.method;
9    assert_eq!(method, rupring::Method::GET);
10
11    let path = request.path;
12    assert_eq!(path, "/");
13
14    let body = request.body;
15    assert_eq!(body, "");
16
17    let headers = request.headers;
18    let content_type = headers.get("content-type").unwrap();
19    assert_eq!(content_type, "text/plain");
20
21    let id = request.path_parameters["id"].clone();
22    assert_eq!(id, "123");
23
24    let query = request.query_parameters["query"].clone();
25    assert_eq!(query, vec!["asdf".to_string()]);
26
27    //...
28
29    response
30}
31```
32
33## Request: Path Param
34
35For path parameters, auto binding is provided through annotation.
36
37The annotation name can be one of `Path`, `path`, or `PathVariable`.
38```rust
39#[rupring::Get(path = /echo/:id)]
40pub fn echo(
41    #[PathVariable="id"] id: i32
42) -> rupring::Response {
43    println!("id: {}", id);
44
45    rupring::Response::new().text(request.body)
46}
47```
48
49If the Path Param is optional, just wrap the type in `Option`.
50```rust
51#[rupring::Get(path = /echo/:id)]
52pub fn echo(
53    #[PathVariable="id"] id: Option<i32>
54) -> rupring::Response {
55    // ...
56
57    rupring::Response::new().text("OK".to_string())
58}
59```
60
61If you need Swagger documentation for the Path Param, you should add the `Description` annotation.
62`Description` can also be used as `Desc`, `desc`, etc.
63```rust
64#[rupring::Get(path = /echo/:id)]
65pub fn echo(
66    #[path="id"] #[desc="asdf"] id: i32
67) -> rupring::Response {
68    println!("id: {}", id);
69
70    rupring::Response::new().text(request.body)
71}
72```
73
74If you want to define a custom type for PathParam, you can implement the ParamStringDeserializer trait.
75```rust
76struct SomeCustomType {}
77
78impl rupring::ParamStringDeserializer<SomeCustomType> for rupring::ParamString {
79    type Error = ();
80
81    fn deserialize(&self) -> Result<SomeCustomType, Self::Error> {
82        //...
83        Ok(SomeCustomType {})
84    }
85}
86```
87*/
88use std::{collections::HashMap, panic::UnwindSafe, sync::Arc};
89
90use hyper::header;
91
92use crate::Method;
93
94#[derive(Debug, Clone)]
95pub struct Request {
96    pub method: Method,
97    pub path: String,
98    pub body: String,
99    pub headers: HashMap<String, String>,
100    pub cookies: HashMap<String, String>,
101    pub query_parameters: HashMap<String, Vec<String>>,
102    pub path_parameters: HashMap<String, String>,
103    pub(crate) di_context: Arc<crate::DIContext>,
104}
105
106impl Request {
107    pub fn parse_cookies_from_headers(&mut self) {
108        if let Some(cookie_header) = self.headers.get(header::COOKIE.as_str()) {
109            for cookie in cookie_header.split("; ") {
110                let mut parts = cookie.splitn(2, '=');
111                if let Some(key) = parts.next() {
112                    if let Some(value) = parts.next() {
113                        self.cookies.insert(key.to_string(), value.to_string());
114                    }
115                }
116            }
117        }
118    }
119}
120
121impl Request {
122    pub fn bind<T: BindFromRequest + Default>(&self) -> anyhow::Result<T> {
123        BindFromRequest::bind(self.clone())
124    }
125}
126
127pub trait BindFromRequest {
128    fn bind(request: Request) -> anyhow::Result<Self>
129    where
130        Self: Sized;
131}
132
133impl UnwindSafe for Request {}
134
135impl Request {
136    pub fn get_provider<T: 'static>(&self) -> Option<&T> {
137        return self.di_context.get::<T>();
138    }
139}
140
141#[derive(Debug, Clone)]
142pub struct QueryString(pub Vec<String>);
143
144pub trait QueryStringDeserializer<T>: Sized {
145    type Error;
146
147    fn deserialize_query_string(&self) -> Result<T, Self::Error>;
148}
149
150impl<T> QueryStringDeserializer<Option<T>> for QueryString
151where
152    QueryString: QueryStringDeserializer<T>,
153{
154    type Error = ();
155
156    fn deserialize_query_string(&self) -> Result<Option<T>, Self::Error> {
157        let result = Self::deserialize_query_string(self);
158
159        match result {
160            Ok(v) => Ok(Some(v)),
161            Err(_) => Ok(None),
162        }
163    }
164}
165
166impl QueryStringDeserializer<i8> for QueryString {
167    type Error = ();
168
169    fn deserialize_query_string(&self) -> Result<i8, Self::Error> {
170        if let Some(e) = self.0.get(0) {
171            e.parse::<i8>().map_err(|_| ())
172        } else {
173            Err(())
174        }
175    }
176}
177
178impl QueryStringDeserializer<i16> for QueryString {
179    type Error = ();
180
181    fn deserialize_query_string(&self) -> Result<i16, Self::Error> {
182        if let Some(e) = self.0.get(0) {
183            e.parse::<i16>().map_err(|_| ())
184        } else {
185            Err(())
186        }
187    }
188}
189
190impl QueryStringDeserializer<i32> for QueryString {
191    type Error = ();
192
193    fn deserialize_query_string(&self) -> Result<i32, Self::Error> {
194        if let Some(e) = self.0.get(0) {
195            e.parse::<i32>().map_err(|_| ())
196        } else {
197            Err(())
198        }
199    }
200}
201
202impl QueryStringDeserializer<i64> for QueryString {
203    type Error = ();
204
205    fn deserialize_query_string(&self) -> Result<i64, Self::Error> {
206        if let Some(e) = self.0.get(0) {
207            e.parse::<i64>().map_err(|_| ())
208        } else {
209            Err(())
210        }
211    }
212}
213
214impl QueryStringDeserializer<i128> for QueryString {
215    type Error = ();
216
217    fn deserialize_query_string(&self) -> Result<i128, Self::Error> {
218        if let Some(e) = self.0.get(0) {
219            e.parse::<i128>().map_err(|_| ())
220        } else {
221            Err(())
222        }
223    }
224}
225
226impl QueryStringDeserializer<isize> for QueryString {
227    type Error = ();
228
229    fn deserialize_query_string(&self) -> Result<isize, Self::Error> {
230        if let Some(e) = self.0.get(0) {
231            e.parse::<isize>().map_err(|_| ())
232        } else {
233            Err(())
234        }
235    }
236}
237
238impl QueryStringDeserializer<u8> for QueryString {
239    type Error = ();
240
241    fn deserialize_query_string(&self) -> Result<u8, Self::Error> {
242        if let Some(e) = self.0.get(0) {
243            e.parse::<u8>().map_err(|_| ())
244        } else {
245            Err(())
246        }
247    }
248}
249
250impl QueryStringDeserializer<u16> for QueryString {
251    type Error = ();
252
253    fn deserialize_query_string(&self) -> Result<u16, Self::Error> {
254        if let Some(e) = self.0.get(0) {
255            e.parse::<u16>().map_err(|_| ())
256        } else {
257            Err(())
258        }
259    }
260}
261
262impl QueryStringDeserializer<u32> for QueryString {
263    type Error = ();
264
265    fn deserialize_query_string(&self) -> Result<u32, Self::Error> {
266        if let Some(e) = self.0.get(0) {
267            e.parse::<u32>().map_err(|_| ())
268        } else {
269            Err(())
270        }
271    }
272}
273
274impl QueryStringDeserializer<u64> for QueryString {
275    type Error = ();
276
277    fn deserialize_query_string(&self) -> Result<u64, Self::Error> {
278        if let Some(e) = self.0.get(0) {
279            e.parse::<u64>().map_err(|_| ())
280        } else {
281            Err(())
282        }
283    }
284}
285
286impl QueryStringDeserializer<u128> for QueryString {
287    type Error = ();
288
289    fn deserialize_query_string(&self) -> Result<u128, Self::Error> {
290        if let Some(e) = self.0.get(0) {
291            e.parse::<u128>().map_err(|_| ())
292        } else {
293            Err(())
294        }
295    }
296}
297
298impl QueryStringDeserializer<usize> for QueryString {
299    type Error = ();
300
301    fn deserialize_query_string(&self) -> Result<usize, Self::Error> {
302        if let Some(e) = self.0.get(0) {
303            e.parse::<usize>().map_err(|_| ())
304        } else {
305            Err(())
306        }
307    }
308}
309
310impl QueryStringDeserializer<f32> for QueryString {
311    type Error = ();
312
313    fn deserialize_query_string(&self) -> Result<f32, Self::Error> {
314        if let Some(e) = self.0.get(0) {
315            e.parse::<f32>().map_err(|_| ())
316        } else {
317            Err(())
318        }
319    }
320}
321
322impl QueryStringDeserializer<f64> for QueryString {
323    type Error = ();
324
325    fn deserialize_query_string(&self) -> Result<f64, Self::Error> {
326        if let Some(e) = self.0.get(0) {
327            e.parse::<f64>().map_err(|_| ())
328        } else {
329            Err(())
330        }
331    }
332}
333
334impl QueryStringDeserializer<bool> for QueryString {
335    type Error = ();
336
337    fn deserialize_query_string(&self) -> Result<bool, Self::Error> {
338        if let Some(e) = self.0.get(0) {
339            e.parse::<bool>().map_err(|_| ())
340        } else {
341            Err(())
342        }
343    }
344}
345
346impl QueryStringDeserializer<String> for QueryString {
347    type Error = ();
348
349    fn deserialize_query_string(&self) -> Result<String, Self::Error> {
350        if let Some(e) = self.0.get(0) {
351            Ok(e.clone())
352        } else {
353            Err(())
354        }
355    }
356}
357
358#[derive(Debug, Clone)]
359pub struct ParamString(pub String);
360
361pub trait ParamStringDeserializer<T>: Sized {
362    type Error;
363
364    fn deserialize(&self) -> Result<T, Self::Error>;
365}
366
367impl<T> ParamStringDeserializer<Option<T>> for ParamString
368where
369    ParamString: ParamStringDeserializer<T>,
370{
371    type Error = ();
372
373    fn deserialize(&self) -> Result<Option<T>, Self::Error> {
374        let result = Self::deserialize(self);
375        match result {
376            Ok(v) => Ok(Some(v)),
377            Err(_) => Ok(None),
378        }
379    }
380}
381
382impl ParamStringDeserializer<i8> for ParamString {
383    type Error = ();
384
385    fn deserialize(&self) -> Result<i8, Self::Error> {
386        self.0.parse::<i8>().map_err(|_| ())
387    }
388}
389
390impl ParamStringDeserializer<i16> for ParamString {
391    type Error = ();
392
393    fn deserialize(&self) -> Result<i16, Self::Error> {
394        self.0.parse::<i16>().map_err(|_| ())
395    }
396}
397
398impl ParamStringDeserializer<i32> for ParamString {
399    type Error = ();
400
401    fn deserialize(&self) -> Result<i32, Self::Error> {
402        self.0.parse::<i32>().map_err(|_| ())
403    }
404}
405
406impl ParamStringDeserializer<i64> for ParamString {
407    type Error = ();
408
409    fn deserialize(&self) -> Result<i64, Self::Error> {
410        self.0.parse::<i64>().map_err(|_| ())
411    }
412}
413
414impl ParamStringDeserializer<i128> for ParamString {
415    type Error = ();
416
417    fn deserialize(&self) -> Result<i128, Self::Error> {
418        self.0.parse::<i128>().map_err(|_| ())
419    }
420}
421
422impl ParamStringDeserializer<isize> for ParamString {
423    type Error = ();
424
425    fn deserialize(&self) -> Result<isize, Self::Error> {
426        self.0.parse::<isize>().map_err(|_| ())
427    }
428}
429
430impl ParamStringDeserializer<u8> for ParamString {
431    type Error = ();
432
433    fn deserialize(&self) -> Result<u8, Self::Error> {
434        self.0.parse::<u8>().map_err(|_| ())
435    }
436}
437
438impl ParamStringDeserializer<u16> for ParamString {
439    type Error = ();
440
441    fn deserialize(&self) -> Result<u16, Self::Error> {
442        self.0.parse::<u16>().map_err(|_| ())
443    }
444}
445
446impl ParamStringDeserializer<u32> for ParamString {
447    type Error = ();
448
449    fn deserialize(&self) -> Result<u32, Self::Error> {
450        self.0.parse::<u32>().map_err(|_| ())
451    }
452}
453
454impl ParamStringDeserializer<u64> for ParamString {
455    type Error = ();
456
457    fn deserialize(&self) -> Result<u64, Self::Error> {
458        self.0.parse::<u64>().map_err(|_| ())
459    }
460}
461
462impl ParamStringDeserializer<u128> for ParamString {
463    type Error = ();
464
465    fn deserialize(&self) -> Result<u128, Self::Error> {
466        self.0.parse::<u128>().map_err(|_| ())
467    }
468}
469
470impl ParamStringDeserializer<usize> for ParamString {
471    type Error = ();
472
473    fn deserialize(&self) -> Result<usize, Self::Error> {
474        self.0.parse::<usize>().map_err(|_| ())
475    }
476}
477
478impl ParamStringDeserializer<f32> for ParamString {
479    type Error = ();
480
481    fn deserialize(&self) -> Result<f32, Self::Error> {
482        self.0.parse::<f32>().map_err(|_| ())
483    }
484}
485
486impl ParamStringDeserializer<f64> for ParamString {
487    type Error = ();
488
489    fn deserialize(&self) -> Result<f64, Self::Error> {
490        self.0.parse::<f64>().map_err(|_| ())
491    }
492}
493
494impl ParamStringDeserializer<bool> for ParamString {
495    type Error = ();
496
497    fn deserialize(&self) -> Result<bool, Self::Error> {
498        self.0.parse::<bool>().map_err(|_| ())
499    }
500}
501
502impl ParamStringDeserializer<String> for ParamString {
503    type Error = ();
504
505    fn deserialize(&self) -> Result<String, Self::Error> {
506        Ok(self.0.clone())
507    }
508}