Skip to main content

ntex/web/
route.rs

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
14/// Connects a handler to the requests it should handle.
15///
16/// A route belongs to a [`Resource`](super::Resource). It does not define a
17/// path itself; instead, its method and custom guards decide which requests
18/// within that resource should reach its handler.
19///
20/// Routes are checked in registration order. A route matches when the request
21/// method matches one of its configured methods and every custom guard accepts
22/// the request. Without a method or custom guard, it matches any request that
23/// reaches the resource.
24///
25/// If a route does not match, the resource tries the next one. When no route
26/// matches, the resource fallback runs and returns `405 Method Not Allowed` by
27/// default.
28///
29/// Use helpers such as [`web::get()`] and [`web::post()`] to create
30/// method-specific routes, then attach a handler with [`Route::to()`] or
31/// [`Route::to_with_state()`]. Handler arguments are populated through
32/// [`FromRequest`], and the returned value is converted into a response through
33/// [`Responder`](super::Responder).
34///
35/// A route without an explicitly configured handler returns `404 Not Found`
36/// when called.
37///
38/// ```rust
39/// use ntex::web::{self, App, HttpResponse};
40///
41/// App::default().service(
42///     web::resource("/users/{id}")
43///         .route(web::get().to(async || "user"))
44///         .route(web::delete().to(async || HttpResponse::NoContent())),
45/// );
46/// ```
47///
48/// [`web::get()`]: super::get()
49/// [`web::post()`]: super::post()
50pub 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    /// Create new route which matches any request.
58    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    /// Moves the route's guards out for promotion to a resource.
67    ///
68    /// Custom guards stay conjunctive, while the configured methods are
69    /// alternatives and become a single method guard.
70    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    /// Add method guard to the route.
114    ///
115    /// ```rust
116    /// # use ntex::web::{self, *};
117    /// # fn main() {
118    /// App::default().service(web::resource("/path").route(
119    ///     web::route()
120    ///         .method(ntex::http::Method::CONNECT)
121    ///         .guard(guard::Header("content-type", "text/plain"))
122    ///         .to(async |req: HttpRequest| { HttpResponse::Ok() }))
123    /// );
124    /// # }
125    /// ```
126    #[must_use]
127    pub fn method(mut self, method: Method) -> Self {
128        self.methods.push(method);
129        self
130    }
131
132    /// Add a match guard to this route.
133    ///
134    /// All guards registered on the route must accept the request. Guards are
135    /// evaluated after the containing resource has matched. If a guard rejects
136    /// the request, the resource tries its next route; if no route matches, the
137    /// resource's default service is used.
138    ///
139    /// Method restrictions added by [`Route::method()`] are evaluated together
140    /// with these guards.
141    ///
142    /// ```rust
143    /// use ntex::web::{self, guard, App};
144    ///
145    /// App::default().service(
146    ///     web::resource("/items")
147    ///         .route(
148    ///             web::get()
149    ///                 .guard(guard::Header("accept", "application/json"))
150    ///                 .to(async || "JSON items")
151    ///         )
152    ///         .route(web::get().to(async || "Default items"))
153    /// );
154    /// ```
155    #[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    /// Set the handler for this route.
162    ///
163    /// Handler arguments are populated through [`FromRequest`]. Each argument
164    /// must implement [`FromRequest`] trait and are evaluated
165    /// before the handler is called. If extraction fails, the error is
166    /// converted into a response.
167    ///
168    /// The handler's return value must implement [`Responder`](super::Responder).
169    /// Use [`Route::to_with_state()`] when the handler also needs a borrowed
170    /// application state and the current request state.
171    ///
172    /// ```rust
173    /// use std::collections::HashMap;
174    /// use ntex::web;
175    ///
176    /// #[derive(serde::Deserialize)]
177    /// struct UserPath {
178    ///     user_id: u32,
179    /// }
180    ///
181    /// async fn show_user(
182    ///     path: web::types::Path<UserPath>,
183    ///     query: web::types::Query<HashMap<String, String>>,
184    /// ) -> String {
185    ///     let format = query.get("format").map(String::as_str).unwrap_or("text");
186    ///     format!("User {} as {format}", path.user_id)
187    /// }
188    ///
189    /// web::App::default().service(
190    ///     web::resource("/users/{user_id}")
191    ///         .route(web::get().to(show_user))
192    /// );
193    /// ```
194    #[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    /// Set a state-aware handler for this route.
206    ///
207    /// The handler receives a shared reference to the application state,
208    /// followed by the current request state and any request extractors.
209    ///
210    /// ```rust
211    /// use ntex::web;
212    ///
213    /// struct AppState {
214    ///     greeting: &'static str,
215    /// }
216    ///
217    /// impl web::State for AppState {
218    ///     type Error = web::DefaultError;
219    /// }
220    ///
221    /// async fn index(
222    ///     state: &AppState,
223    ///     request_state: (),
224    ///     name: web::types::Path<String>,
225    /// ) -> String {
226    ///     let _ = request_state;
227    ///     format!("{}, {}!", state.greeting, name.into_inner())
228    /// }
229    ///
230    /// web::App::<AppState>::new().service(
231    ///     web::resource("/{name}").route(web::get().to_with_state(index))
232    /// );
233    /// ```
234    #[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    // `None` when the route has no custom guards
260    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    /// Builds the route handler future in `fut`, without service readiness.
274    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        // Built in place, the handler future is too large to move cheaply
307        let mut fut = pin!(HandlerFuture::empty());
308        self.handler.call(ctx.st(), req, fut.as_mut());
309        Ok(fut.await)
310    }
311}
312
313/// Convert object to a vec of routes
314pub trait IntoRoutes<St: State, In> {
315    /// Convert into a list of routes.
316    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    /// STATEMENT: Routes dispatch by method and guards and render handler results or errors.
382    ///
383    /// HOW:
384    /// - Register synchronous-result and delayed handlers, including a header-guarded PATCH route.
385    /// - Exercise supported, guarded, and unsupported methods and assert their distinct statuses.
386    /// - Check a JSON handler's exact body and inspect route/factory debug metadata and creation.
387    #[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    /// STATEMENT: Route arrays select handlers independently of another route's extractor failures.
497    ///
498    /// HOW:
499    /// - Register GET with a numeric `Path` extractor and POST without that extractor.
500    /// - Assert numeric GET returns its value, invalid GET returns 404, and invalid-path POST returns 201.
501    #[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    /// STATEMENT: Route debug output distinguishes stateless and state-aware handlers.
528    ///
529    /// HOW:
530    /// - Build routes with `to` and `to_with_state` and format them.
531    /// - Assert their debug output identifies `HandlerNoState` and `HandlerSt`, respectively.
532    #[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    /// STATEMENT: Path-based route helpers keep a route's methods as alternatives and its custom guards as requirements.
545    ///
546    /// HOW:
547    /// - Register a GET-or-POST route requiring an `x-ok` header through `App::route`, continued `AppServices::route`, `Scope::route`, continued `ScopeServices::route`, and `ServiceConfig::route`.
548    /// - For every path, assert GET and POST with the header reach the handler, while PUT and GET without the header return `404 Not Found`.
549    /// - Register a PUT route on the `App::route` path and assert PUT falls through to that separate resource.
550    #[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}