1use 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#[derive(Debug, Copy, Clone, PartialEq, Eq)]
34pub(crate) struct RemoteAddr(pub(crate) SocketAddr);
35
36mod private {
37 pub trait Sealed {}
38}
39
40pub trait RequestExt: private::Sealed {
48 fn extract_from_head<E>(&mut self) -> impl Future<Output = Result<E>> + Send
64 where
65 E: FromRequestHead + 'static;
66
67 #[must_use]
82 fn context(&self) -> &crate::ProjectContext;
83
84 #[must_use]
99 fn project_config(&self) -> &crate::config::ProjectConfig;
100
101 #[must_use]
116 fn router(&self) -> &Arc<Router>;
117
118 fn app_name(&self) -> Option<&str>;
137
138 #[must_use]
160 fn route_name(&self) -> Option<&str>;
161
162 #[must_use]
177 fn path_params(&self) -> &PathParams;
178
179 #[must_use]
194 fn path_params_mut(&mut self) -> &mut PathParams;
195
196 #[must_use]
211 fn content_type(&self) -> Option<&http::HeaderValue>;
212
213 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 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 assert!(request.expect_content_type("text/plain").is_ok());
461
462 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}