Skip to main content

cot/
request.rs

1//! HTTP request type and helper methods.
2//!
3//! Cot uses the [`Request`](http::Request) type from the [`http`] crate
4//! to represent incoming HTTP requests. However, it also provides a
5//! [`RequestExt`] trait that contains various helper methods for working with
6//! HTTP requests. These methods are used to access the application context,
7//! project configuration, path parameters, and more. You probably want to have
8//! a `use` statement for [`RequestExt`] in your code most of the time to be
9//! able to use these functions:
10//!
11//! ```
12//! use cot::request::RequestExt;
13//! ```
14
15use std::future::Future;
16use std::net::SocketAddr;
17use std::sync::Arc;
18
19use cot_core::request::{AppName, InvalidContentType, RouteName};
20#[doc(inline)]
21pub use cot_core::request::{PathParams, PathParamsDeserializerError, Request, RequestHead};
22use http::Extensions;
23
24use crate::Result;
25use crate::request::extractors::FromRequestHead;
26use crate::router::Router;
27
28pub mod extractors;
29
30/// The address of the peer that sent the request, as seen by the server.
31///
32/// Inserted into the request extensions for every accepted connection.
33#[derive(Debug, Copy, Clone, PartialEq, Eq)]
34pub(crate) struct RemoteAddr(pub(crate) SocketAddr);
35
36mod private {
37    pub trait Sealed {}
38}
39
40/// Extension trait for [`http::Request`] that provides helper methods for
41/// working with HTTP requests.
42///
43/// # Sealed
44///
45/// This trait is sealed since it doesn't make sense to be implemented for types
46/// outside the context of Cot.
47pub trait RequestExt: private::Sealed {
48    /// Runs an extractor implementing [`FromRequestHead`] on the request.
49    ///
50    /// # Examples
51    ///
52    /// ```
53    /// use cot::request::extractors::Path;
54    /// use cot::request::{Request, RequestExt};
55    /// use cot::response::Response;
56    ///
57    /// async fn my_handler(mut request: Request) -> cot::Result<Response> {
58    ///     let path_params = request.extract_from_head::<Path<String>>().await?;
59    ///     // ...
60    ///     # unimplemented!()
61    /// }
62    /// ```
63    fn extract_from_head<E>(&mut self) -> impl Future<Output = Result<E>> + Send
64    where
65        E: FromRequestHead + 'static;
66
67    /// Get the application context.
68    ///
69    /// # Examples
70    ///
71    /// ```
72    /// use cot::request::{Request, RequestExt};
73    /// use cot::response::Response;
74    ///
75    /// async fn my_handler(mut request: Request) -> cot::Result<Response> {
76    ///     let context = request.context();
77    ///     // ... do something with the context
78    ///     # unimplemented!()
79    /// }
80    /// ```
81    #[must_use]
82    fn context(&self) -> &crate::ProjectContext;
83
84    /// Get the project configuration.
85    ///
86    /// # Examples
87    ///
88    /// ```
89    /// use cot::request::{Request, RequestExt};
90    /// use cot::response::Response;
91    ///
92    /// async fn my_handler(mut request: Request) -> cot::Result<Response> {
93    ///     let config = request.project_config();
94    ///     // ... do something with the config
95    ///     # unimplemented!()
96    /// }
97    /// ```
98    #[must_use]
99    fn project_config(&self) -> &crate::config::ProjectConfig;
100
101    /// Get the router.
102    ///
103    /// # Examples
104    ///
105    /// ```
106    /// use cot::request::{Request, RequestExt};
107    /// use cot::response::Response;
108    ///
109    /// async fn my_handler(mut request: Request) -> cot::Result<Response> {
110    ///     let router = request.router();
111    ///     // ... do something with the router
112    ///     # unimplemented!()
113    /// }
114    /// ```
115    #[must_use]
116    fn router(&self) -> &Arc<Router>;
117
118    /// Returns the name of the app that the current route belongs to, or
119    /// [`None`] if the request is not routed.
120    ///
121    /// This is mainly useful for providing context to reverse redirects, where
122    /// you want to redirect to a route in the same app.
123    ///
124    /// # Examples
125    ///
126    /// ```
127    /// use cot::request::{Request, RequestExt};
128    /// use cot::response::Response;
129    ///
130    /// async fn my_handler(mut request: Request) -> cot::Result<Response> {
131    ///     let app_name = request.app_name();
132    ///     // ... do something with the app name
133    ///     # unimplemented!()
134    /// }
135    /// ```
136    fn app_name(&self) -> Option<&str>;
137
138    /// Returns the name of the current route.
139    ///
140    /// This returns [`None`] if:
141    /// - the request is not routed, or
142    /// - the route has no name.
143    ///
144    /// This is mainly useful for use in templates, where you want to know which
145    /// route is being rendered, for instance to mark the active tab.
146    ///
147    /// # Examples
148    ///
149    /// ```
150    /// use cot::request::{Request, RequestExt};
151    /// use cot::response::Response;
152    ///
153    /// async fn my_handler(mut request: Request) -> cot::Result<Response> {
154    ///     let route_name = request.route_name();
155    ///     // ... do something with the route name
156    ///     # unimplemented!()
157    /// }
158    /// ```
159    #[must_use]
160    fn route_name(&self) -> Option<&str>;
161
162    /// Get the path parameters.
163    ///
164    /// # Examples
165    ///
166    /// ```
167    /// use cot::request::{Request, RequestExt};
168    /// use cot::response::Response;
169    ///
170    /// async fn my_handler(mut request: Request) -> cot::Result<Response> {
171    ///     let path_params = request.path_params();
172    ///     // ... do something with the path params
173    ///     # unimplemented!()
174    /// }
175    /// ```
176    #[must_use]
177    fn path_params(&self) -> &PathParams;
178
179    /// Get the path parameters mutably.
180    ///
181    /// # Examples
182    ///
183    /// ```
184    /// use cot::request::{Request, RequestExt};
185    /// use cot::response::Response;
186    ///
187    /// async fn my_handler(mut request: Request) -> cot::Result<Response> {
188    ///     let path_params = request.path_params_mut();
189    ///     // ... do something with the path params
190    ///     # unimplemented!()
191    /// }
192    /// ```
193    #[must_use]
194    fn path_params_mut(&mut self) -> &mut PathParams;
195
196    /// Get the content type of the request.
197    ///
198    /// # Examples
199    ///
200    /// ```
201    /// use cot::request::{Request, RequestExt};
202    /// use cot::response::Response;
203    ///
204    /// async fn my_handler(mut request: Request) -> cot::Result<Response> {
205    ///     let content_type = request.content_type();
206    ///     // ... do something with the content type
207    ///     # unimplemented!()
208    /// }
209    /// ```
210    #[must_use]
211    fn content_type(&self) -> Option<&http::HeaderValue>;
212
213    /// Expect the content type of the request to be the given value.
214    ///
215    /// # Errors
216    ///
217    /// Returns an error if the content type is not the expected value.
218    ///
219    /// # Examples
220    ///
221    /// ```
222    /// use cot::request::{Request, RequestExt};
223    /// use cot::response::Response;
224    ///
225    /// async fn my_handler(mut request: Request) -> cot::Result<Response> {
226    ///     request.expect_content_type("application/json")?;
227    ///     // ...
228    ///     # unimplemented!()
229    /// }
230    /// ```
231    fn expect_content_type(&mut self, expected: &'static str) -> Result<()> {
232        let content_type = self
233            .content_type()
234            .map_or("".into(), |value| String::from_utf8_lossy(value.as_bytes()));
235        if content_type == expected {
236            Ok(())
237        } else {
238            Err(InvalidContentType {
239                expected,
240                actual: content_type.into_owned(),
241            }
242            .into())
243        }
244    }
245
246    #[doc(hidden)]
247    fn extensions(&self) -> &Extensions;
248}
249
250impl private::Sealed for Request {}
251
252impl RequestExt for Request {
253    async fn extract_from_head<E>(&mut self) -> Result<E>
254    where
255        E: FromRequestHead + 'static,
256    {
257        let request = std::mem::take(self);
258
259        let (head, body) = request.into_parts();
260        let result = E::from_request_head(&head).await;
261
262        *self = Request::from_parts(head, body);
263        result
264    }
265
266    #[track_caller]
267    fn context(&self) -> &crate::ProjectContext {
268        self.extensions()
269            .get::<Arc<crate::ProjectContext>>()
270            .expect("AppContext extension missing")
271    }
272
273    fn project_config(&self) -> &crate::config::ProjectConfig {
274        self.context().config()
275    }
276
277    fn router(&self) -> &Arc<Router> {
278        self.context().router()
279    }
280
281    fn app_name(&self) -> Option<&str> {
282        self.extensions()
283            .get::<AppName>()
284            .map(|AppName(name)| name.as_str())
285    }
286
287    fn route_name(&self) -> Option<&str> {
288        self.extensions()
289            .get::<RouteName>()
290            .map(|RouteName(name)| name.as_str())
291    }
292
293    #[track_caller]
294    fn path_params(&self) -> &PathParams {
295        self.extensions()
296            .get::<PathParams>()
297            .expect("PathParams extension missing")
298    }
299
300    fn path_params_mut(&mut self) -> &mut PathParams {
301        self.extensions_mut().get_or_insert_default::<PathParams>()
302    }
303
304    fn content_type(&self) -> Option<&http::HeaderValue> {
305        self.headers().get(http::header::CONTENT_TYPE)
306    }
307
308    fn extensions(&self) -> &Extensions {
309        self.extensions()
310    }
311}
312
313impl private::Sealed for RequestHead {}
314
315impl RequestExt for RequestHead {
316    async fn extract_from_head<E>(&mut self) -> Result<E>
317    where
318        E: FromRequestHead + 'static,
319    {
320        E::from_request_head(self).await
321    }
322
323    fn context(&self) -> &crate::ProjectContext {
324        self.extensions
325            .get::<Arc<crate::ProjectContext>>()
326            .expect("AppContext extension missing")
327    }
328
329    fn project_config(&self) -> &crate::config::ProjectConfig {
330        self.context().config()
331    }
332
333    fn router(&self) -> &Arc<Router> {
334        self.context().router()
335    }
336
337    fn app_name(&self) -> Option<&str> {
338        self.extensions
339            .get::<AppName>()
340            .map(|AppName(name)| name.as_str())
341    }
342
343    fn route_name(&self) -> Option<&str> {
344        self.extensions
345            .get::<RouteName>()
346            .map(|RouteName(name)| name.as_str())
347    }
348
349    fn path_params(&self) -> &PathParams {
350        self.extensions
351            .get::<PathParams>()
352            .expect("PathParams extension missing")
353    }
354
355    fn path_params_mut(&mut self) -> &mut PathParams {
356        self.extensions.get_or_insert_default::<PathParams>()
357    }
358
359    fn content_type(&self) -> Option<&http::HeaderValue> {
360        self.headers.get(http::header::CONTENT_TYPE)
361    }
362
363    fn extensions(&self) -> &Extensions {
364        &self.extensions
365    }
366}
367
368#[cfg(test)]
369mod tests {
370    use super::*;
371    use crate::Body;
372    use crate::request::extractors::Path;
373    use crate::response::Response;
374    use crate::router::{Route, Router};
375    use crate::test::TestRequestBuilder;
376
377    #[test]
378    fn request_ext_app_name() {
379        let mut request = TestRequestBuilder::get("/").build();
380        assert_eq!(request.app_name(), None);
381
382        request
383            .extensions_mut()
384            .insert(AppName("test_app".to_string()));
385        assert_eq!(request.app_name(), Some("test_app"));
386    }
387
388    #[test]
389    fn request_ext_route_name() {
390        let mut request = TestRequestBuilder::get("/").build();
391        assert_eq!(request.route_name(), None);
392
393        request
394            .extensions_mut()
395            .insert(RouteName("test_route".to_string()));
396        assert_eq!(request.route_name(), Some("test_route"));
397    }
398
399    #[test]
400    fn request_ext_parts_route_name() {
401        let request = TestRequestBuilder::get("/").build();
402        let (mut head, _body) = request.into_parts();
403        assert_eq!(head.route_name(), None);
404
405        head.extensions.insert(RouteName("test_route".to_string()));
406        assert_eq!(head.route_name(), Some("test_route"));
407    }
408
409    #[test]
410    fn request_ext_path_params() {
411        let mut request = TestRequestBuilder::get("/").build();
412
413        let mut params = PathParams::new();
414        params.insert("id".to_string(), "42".to_string());
415        request.extensions_mut().insert(params);
416
417        assert_eq!(request.path_params().get("id"), Some("42"));
418    }
419
420    #[test]
421    fn request_ext_path_params_mut() {
422        let mut request = TestRequestBuilder::get("/").build();
423
424        request
425            .path_params_mut()
426            .insert("id".to_string(), "42".to_string());
427
428        assert_eq!(request.path_params().get("id"), Some("42"));
429    }
430
431    #[test]
432    fn request_ext_content_type() {
433        let mut request = TestRequestBuilder::get("/").build();
434        assert_eq!(request.content_type(), None);
435
436        request.headers_mut().insert(
437            http::header::CONTENT_TYPE,
438            http::HeaderValue::from_static("text/plain"),
439        );
440
441        assert_eq!(
442            request.content_type(),
443            Some(&http::HeaderValue::from_static("text/plain"))
444        );
445    }
446
447    #[test]
448    fn request_ext_expect_content_type() {
449        let mut request = TestRequestBuilder::get("/").build();
450
451        // Should fail with no content type
452        assert!(request.expect_content_type("text/plain").is_err());
453
454        request.headers_mut().insert(
455            http::header::CONTENT_TYPE,
456            http::HeaderValue::from_static("text/plain"),
457        );
458
459        // Should succeed with matching content type
460        assert!(request.expect_content_type("text/plain").is_ok());
461
462        // Should fail with non-matching content type
463        assert!(request.expect_content_type("application/json").is_err());
464    }
465
466    #[cot::test]
467    async fn request_ext_extract_from_head() {
468        async fn handler(mut request: Request) -> Result<Response> {
469            let Path(id): Path<String> = request.extract_from_head().await?;
470            assert_eq!(id, "42");
471
472            Ok(Response::new(Body::empty()))
473        }
474
475        let router = Router::with_urls([Route::with_handler("/{id}/", handler)]);
476
477        let request = TestRequestBuilder::get("/42/")
478            .router(router.clone())
479            .build();
480
481        router.handle(request).await.unwrap();
482    }
483
484    #[test]
485    fn parts_ext_path_params() {
486        let (mut head, _) = Request::new(Body::empty()).into_parts();
487        let mut params = PathParams::new();
488        params.insert("id".to_string(), "42".to_string());
489        head.extensions.insert(params);
490
491        assert_eq!(head.path_params().get("id"), Some("42"));
492    }
493
494    #[test]
495    fn parts_ext_mutating_path_params() {
496        let (mut head, _) = Request::new(Body::empty()).into_parts();
497        head.path_params_mut()
498            .insert("page".to_string(), "1".to_string());
499
500        assert_eq!(head.path_params().get("page"), Some("1"));
501    }
502
503    #[test]
504    fn parts_ext_app_name() {
505        let (mut head, _) = Request::new(Body::empty()).into_parts();
506        head.extensions.insert(AppName("test_app".to_string()));
507
508        assert_eq!(head.app_name(), Some("test_app"));
509    }
510
511    #[test]
512    fn parts_ext_route_name() {
513        let (mut head, _) = Request::new(Body::empty()).into_parts();
514        head.extensions.insert(RouteName("test_route".to_string()));
515
516        assert_eq!(head.route_name(), Some("test_route"));
517    }
518
519    #[test]
520    fn parts_ext_content_type() {
521        let (mut head, _) = Request::new(Body::empty()).into_parts();
522        head.headers.insert(
523            http::header::CONTENT_TYPE,
524            http::HeaderValue::from_static("text/plain"),
525        );
526
527        assert_eq!(
528            head.content_type(),
529            Some(&http::HeaderValue::from_static("text/plain"))
530        );
531    }
532
533    #[cot::test]
534    async fn path_extract_from_head() {
535        let (mut head, _) = Request::new(Body::empty()).into_parts();
536
537        let mut params = PathParams::new();
538        params.insert("id".to_string(), "42".to_string());
539        head.extensions.insert(params);
540
541        let Path(id): Path<String> = head.extract_from_head().await.unwrap();
542        assert_eq!(id, "42");
543    }
544}