1use std::{fmt, mem, pin::Pin, pin::pin, rc::Rc};
2
3use crate::error::Failure;
4use crate::http::Method;
5use crate::service::{Ctx, Service, ServiceFactory};
6
7use super::error::{WebError, WebResponseError};
8use super::guard::{self, AllGuard, Guard};
9use super::handler::{
10 Handler, HandlerFn, HandlerFuture, HandlerSt, HandlerStWrapper, HandlerWrapper,
11};
12use super::{FromRequest, HttpResponse, State, WebRequest, WebResponse};
13
14pub struct Route<St: State, In = ()> {
51 handler: Rc<dyn HandlerFn<St, In>>,
52 methods: Vec<Method>,
53 guards: Rc<AllGuard>,
54}
55
56impl<St: State, In: 'static> Route<St, In> {
57 pub fn new() -> Route<St, In> {
59 Route {
60 handler: HandlerWrapper::<St, In, _, ()>::create(async || HttpResponse::NotFound()),
61 methods: Vec::new(),
62 guards: Rc::default(),
63 }
64 }
65
66 pub(super) fn take_guards(&mut self) -> Vec<Box<dyn Guard>> {
71 let mut guards = mem::take(&mut Rc::get_mut(&mut self.guards).unwrap().0);
72 match self.methods.as_slice() {
73 [] => (),
74 [method] => guards.push(Box::new(guard::Method(method.clone()))),
75 methods => guards.push(Box::new(guard::AnyGuard(
76 methods
77 .iter()
78 .map(|m| Box::new(guard::Method(m.clone())) as Box<dyn Guard>)
79 .collect(),
80 ))),
81 }
82 guards
83 }
84
85 pub(super) fn service(&self) -> RouteService<St, In> {
86 RouteService {
87 handler: self.handler.clone(),
88 guards: (!self.guards.0.is_empty()).then(|| self.guards.clone()),
89 methods: self.methods.clone(),
90 }
91 }
92}
93
94impl<St: State, In: 'static> Default for Route<St, In> {
95 fn default() -> Self {
96 Self::new()
97 }
98}
99
100impl<St: State, In: 'static> ServiceFactory<St, WebRequest<In>> for Route<St, In> {
101 type Res = WebResponse;
102 type Error = WebError<St, St::Error>;
103
104 type Service = RouteService<St, In>;
105 type InitError = Failure;
106
107 async fn create(&self, _: &St) -> Result<Self::Service, Self::InitError> {
108 Ok(self.service())
109 }
110}
111
112impl<St: State, In: 'static> Route<St, In> {
113 #[must_use]
127 pub fn method(mut self, method: Method) -> Self {
128 self.methods.push(method);
129 self
130 }
131
132 #[must_use]
156 pub fn guard<F: Guard + 'static>(mut self, f: F) -> Self {
157 Rc::get_mut(&mut self.guards).unwrap().add(f);
158 self
159 }
160
161 #[must_use]
195 pub fn to<H, Args>(mut self, handler: H) -> Self
196 where
197 H: Handler<St, Args> + 'static,
198 Args: FromRequest<St> + 'static,
199 Args::Error: WebResponseError<St, St::Error>,
200 {
201 self.handler = HandlerWrapper::create(handler);
202 self
203 }
204
205 #[must_use]
235 pub fn to_with_state<H, Args>(mut self, handler: H) -> Self
236 where
237 H: HandlerSt<St, In, Args> + 'static,
238 Args: FromRequest<St> + 'static,
239 Args::Error: WebResponseError<St, St::Error>,
240 {
241 self.handler = HandlerStWrapper::create(handler);
242 self
243 }
244}
245
246impl<St: State, In> fmt::Debug for Route<St, In> {
247 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
248 f.debug_struct("Route")
249 .field("handler", &self.handler)
250 .field("methods", &self.methods)
251 .field("guards", &self.guards)
252 .finish()
253 }
254}
255
256pub struct RouteService<St: State, In> {
257 handler: Rc<dyn HandlerFn<St, In>>,
258 methods: Vec<Method>,
259 guards: Option<Rc<AllGuard>>,
261}
262
263impl<St: State, In> RouteService<St, In> {
264 #[inline]
265 pub fn check(&self, req: &mut WebRequest<In>) -> bool {
266 if !self.methods.is_empty() && !self.methods.contains(&req.head().method) {
267 return false;
268 }
269
270 self.guards.as_ref().is_none_or(|g| g.check(req.head()))
271 }
272
273 pub(super) fn handle<'a>(
275 &'a self,
276 st: &'a St,
277 req: WebRequest<In>,
278 fut: Pin<&mut HandlerFuture<'a>>,
279 ) {
280 self.handler.call(st, req, fut);
281 }
282}
283
284impl<St: State, In> fmt::Debug for RouteService<St, In> {
285 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
286 f.debug_struct("RouteService")
287 .field("handler", &self.handler)
288 .field("methods", &self.methods)
289 .field(
290 "guards",
291 &self.guards.as_deref().unwrap_or(&AllGuard::default()),
292 )
293 .finish()
294 }
295}
296
297impl<St: State, In> Service<St, WebRequest<In>> for RouteService<St, In> {
298 type Res = WebResponse;
299 type Error = WebError<St, St::Error>;
300
301 async fn call(
302 &self,
303 req: WebRequest<In>,
304 ctx: Ctx<'_, Self, St>,
305 ) -> Result<Self::Res, Self::Error> {
306 let mut fut = pin!(HandlerFuture::empty());
308 self.handler.call(ctx.st(), req, fut.as_mut());
309 Ok(fut.await)
310 }
311}
312
313pub trait IntoRoutes<St: State, In> {
315 fn routes(self) -> Vec<Route<St, In>>;
317}
318
319impl<St: State, In> IntoRoutes<St, In> for Route<St, In> {
320 fn routes(self) -> Vec<Route<St, In>> {
321 vec![self]
322 }
323}
324
325impl<St: State, In> IntoRoutes<St, In> for Vec<Route<St, In>> {
326 fn routes(self) -> Vec<Route<St, In>> {
327 self
328 }
329}
330
331macro_rules! tuple_routes(
332 {$(#[$meta:meta])* $(($n:tt, $T:ident)),+} => {
333 $(#[$meta])*
334 #[allow(unused_parens)]
335 impl<St: State, U, $($T,)+> IntoRoutes<St, U> for ($($T,)+)
336 where
337 $($T: Into<Route<St, U>> + 'static,)+ {
338 fn routes(self) -> Vec<Route<St, U>> {
339 vec![$(self.$n.into(),)+]
340 }
341 }
342 }
343);
344
345impl<St: State, In, T, const N: usize> IntoRoutes<St, In> for [T; N]
346where
347 T: Into<Route<St, In>>,
348{
349 fn routes(self) -> Vec<Route<St, In>> {
350 let mut routes = Vec::with_capacity(N);
351 for route in self {
352 routes.push(route.into());
353 }
354 routes
355 }
356}
357
358#[allow(clippy::wildcard_imports)]
359#[rustfmt::skip]
360mod m {
361 use variadics_please::all_tuples_enumerated;
362
363 use super::*;
364
365 all_tuples_enumerated!(#[doc(fake_variadic)] tuple_routes, 1, 12, T);
366}
367
368#[cfg(test)]
369mod tests {
370 use crate::http::{Method, StatusCode, header};
371 use crate::time::{Millis, sleep};
372 use crate::web::test::{TestRequest, call_service, init_service, read_body};
373 use crate::web::{self, App, HttpResponse, error, guard};
374 use crate::{ServiceFactory, util::Bytes};
375
376 #[derive(serde::Serialize, PartialEq, Debug)]
377 struct MyObject {
378 name: String,
379 }
380
381 #[crate::rt_test]
388 async fn test_route() {
389 let srv = init_service(
390 App::new()
391 .service(web::resource("/test").route(vec![
392 web::get().to(async || { HttpResponse::Ok() }),
393 web::put().to(async || {
394 Err::<HttpResponse, _>(
395 error::ErrorBadRequest::<_>("err"),
396 )
397 }),
398 web::post().to(async || {
399 sleep(Millis(100)).await;
400 HttpResponse::Created()
401 }),
402 web::patch()
403 .guard(guard::fn_guard(|req|
404 req.headers().contains_key("content-type")
405 ))
406 .to(async || { HttpResponse::Conflict() }),
407 web::delete().to(async || {
408 sleep(Millis(100)).await;
409 Err::<HttpResponse, _>(error::ErrorBadRequest("err"))
410 }),
411 ]))
412 .service(web::resource("/json").route(web::get().to(async || {
413 sleep(Millis(25)).await;
414 web::types::Json(MyObject {
415 name: "test".to_string(),
416 })
417 }))),
418 )
419 .await;
420
421 let req = TestRequest::with_uri("/test")
422 .method(Method::GET)
423 .to_request();
424 let resp = call_service(&srv, req).await;
425 assert_eq!(resp.status(), StatusCode::OK);
426
427 let req = TestRequest::with_uri("/test")
428 .method(Method::POST)
429 .to_request();
430 let resp = call_service(&srv, req).await;
431 assert_eq!(resp.status(), StatusCode::CREATED);
432
433 let req = TestRequest::with_uri("/test")
434 .method(Method::PUT)
435 .to_request();
436 let resp = call_service(&srv, req).await;
437 assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
438
439 let req = TestRequest::with_uri("/test")
440 .method(Method::PATCH)
441 .to_request();
442 let resp = call_service(&srv, req).await;
443 assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
444
445 let req = TestRequest::with_uri("/test")
446 .method(Method::PATCH)
447 .header(header::CONTENT_TYPE, "text/plain")
448 .to_request();
449 let resp = call_service(&srv, req).await;
450 assert_eq!(resp.status(), StatusCode::CONFLICT);
451
452 let req = TestRequest::with_uri("/test")
453 .method(Method::DELETE)
454 .to_request();
455 let resp = call_service(&srv, req).await;
456 assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
457
458 let req = TestRequest::with_uri("/test")
459 .method(Method::HEAD)
460 .to_request();
461 let resp = call_service(&srv, req).await;
462 assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
463
464 let req = TestRequest::with_uri("/json").to_request();
465 let resp = call_service(&srv, req).await;
466 assert_eq!(resp.status(), StatusCode::OK);
467
468 let body = read_body(resp).await;
469 assert_eq!(body, Bytes::from_static(b"{\"name\":\"test\"}"));
470
471 let route: web::Route<(), ()> = web::get();
472 let repr = format!("{route:?}");
473 assert!(repr.contains("Route"), "{}", repr);
474 assert!(
475 repr.contains(
476 "handler: HandlerNoState(\"ntex::web::route::Route<()>::new::{{closure}}\")"
477 ),
478 "{}",
479 repr
480 );
481 assert!(repr.contains("methods: [GET]"), "{}", repr);
482 assert!(repr.contains("guards: AllGuard()"), "{}", repr);
483
484 assert!(route.create(&()).await.is_ok());
485
486 let route_service = route.service();
487 let repr = format!("{route_service:?}");
488 assert!(repr.contains("RouteService"));
489 assert!(repr.contains(
490 "handler: HandlerNoState(\"ntex::web::route::Route<()>::new::{{closure}}\")"
491 ));
492 assert!(repr.contains("methods: [GET]"));
493 assert!(repr.contains("guards: AllGuard()"));
494 }
495
496 #[crate::rt_test]
502 async fn test_route_array_and_extractor_error() {
503 let srv = init_service(App::new().service(web::resource("/test/{id}").route([
504 web::get().to(async |p: web::types::Path<u32>| {
505 HttpResponse::Ok().body(format!("{}", p.into_inner()))
506 }),
507 web::post().to(async || HttpResponse::Created()),
508 ])))
509 .await;
510
511 let req = TestRequest::with_uri("/test/10").to_request();
512 let resp = call_service(&srv, req).await;
513 assert_eq!(resp.status(), StatusCode::OK);
514 assert_eq!(read_body(resp).await, Bytes::from_static(b"10"));
515
516 let req = TestRequest::with_uri("/test/abc").to_request();
517 let resp = call_service(&srv, req).await;
518 assert_eq!(resp.status(), StatusCode::NOT_FOUND);
519
520 let req = TestRequest::with_uri("/test/abc")
521 .method(Method::POST)
522 .to_request();
523 let resp = call_service(&srv, req).await;
524 assert_eq!(resp.status(), StatusCode::CREATED);
525 }
526
527 #[test]
533 fn test_route_debug() {
534 let route: web::Route<(), ()> = web::get().to(async || HttpResponse::Ok());
535 let s = format!("{route:?}");
536 assert!(s.contains("HandlerNoState"), "{s}");
537
538 let route =
539 web::Route::<(), ()>::new().to_with_state(async |(): &(), (): ()| HttpResponse::Ok());
540 let s = format!("{route:?}");
541 assert!(s.contains("HandlerSt("), "{s}");
542 }
543
544 #[crate::rt_test]
551 async fn test_route_helpers_promote_method_alternatives() {
552 fn multi() -> web::Route<()> {
553 web::route()
554 .method(Method::GET)
555 .method(Method::POST)
556 .guard(guard::Header("x-ok", "1"))
557 .to(async || HttpResponse::Ok())
558 }
559
560 let srv = init_service(
561 App::new()
562 .route("/a", multi())
563 .route("/b", multi())
564 .route("/a", web::put().to(async || HttpResponse::Created()))
565 .service(web::scope("/s").route("/a", multi()).route("/b", multi()))
566 .service(web::scope("/c").configure(|cfg| {
567 cfg.route("/a", multi());
568 })),
569 )
570 .await;
571
572 for path in ["/a", "/b", "/s/a", "/s/b", "/c/a"] {
573 let call = async |method: Method, header: bool| {
574 let mut req = TestRequest::with_uri(path).method(method);
575 if header {
576 req = req.header("x-ok", "1");
577 }
578 call_service(&srv, req.to_request()).await.status()
579 };
580 assert_eq!(call(Method::GET, true).await, StatusCode::OK, "{path}");
581 assert_eq!(call(Method::POST, true).await, StatusCode::OK, "{path}");
582 assert_eq!(
583 call(Method::GET, false).await,
584 StatusCode::NOT_FOUND,
585 "{path}"
586 );
587 let put = if path == "/a" {
588 StatusCode::CREATED
589 } else {
590 StatusCode::NOT_FOUND
591 };
592 assert_eq!(call(Method::PUT, true).await, put, "{path}");
593 }
594 }
595}