Skip to main content

ntex/web/
scope.rs

1use std::{cell::RefCell, marker::PhantomData, rc::Rc};
2
3use crate::error::{Failure, IntoFailure};
4use crate::http::Response;
5use crate::router::{IntoPattern, ResourceDef, Router};
6use crate::service::{Identity, ServiceChainFactory, boxed};
7use crate::{IntoServiceFactory, Middleware, Service, ServiceFactory, factory};
8
9use super::app_service::WebServiceRouter;
10use super::dev::{WebServiceConfig, WebServiceFactory};
11use super::error::{WebError, WebResponseError};
12use super::guard::Guard;
13use super::rmap::ResourceMap;
14use super::service::{AppServiceFactory, ServiceFactoryWrapper, WebRoute};
15use super::stack::{Filter, WebStack};
16use super::{HttpService, Resource, Route, ServiceConfig, State, WebRequest, WebResponse};
17
18type Guards = Vec<Box<dyn Guard>>;
19
20/// Groups services under a shared path prefix.
21///
22/// A scope is useful for keeping a related part of an application together,
23/// such as an API or administration area. It can contain resources, routes,
24/// nested scopes, middleware, filters, guards, and its own fallback service.
25///
26/// The prefix matches complete path segments. For example, `scope("/api")`
27/// can contain a service for `/api/users`, but the scope itself does not match
28/// the bare `/api` path. Register an empty nested resource if that path also
29/// needs a handler.
30///
31/// Scope prefixes can contain dynamic segments. Their values remain available
32/// to nested handlers through [`HttpRequest::match_info()`] and the [`Path`]
33/// extractor. For example, `scope("/users/{user_id}")` makes `user_id`
34/// available to every handler nested inside that scope.
35///
36/// Once the scope's prefix and guards match, its middleware and filters run,
37/// followed by its nested router. If no nested service matches, the scope uses
38/// its own fallback, which returns `404 Not Found` by default. It does not fall
39/// back to the surrounding application.
40///
41/// ```rust
42/// use ntex::web::{self, App};
43///
44/// async fn issues(
45///     path: web::types::Path<(String,)>,
46/// ) -> String {
47///     format!("Issues for {}", path.0)
48/// }
49///
50/// App::default().service(
51///     web::scope("/projects/{project_id}")
52///         .route("/issues", web::get().to(issues))
53///         .route("/settings", web::get().to(async || "settings")),
54/// );
55/// ```
56///
57/// [`HttpRequest::match_info()`]: super::HttpRequest::match_info
58/// [`Path`]: super::types::Path
59#[derive(derive_more::Debug)]
60#[debug("Scope({rdef:?})")]
61pub struct Scope<St: State, In, Out = In, M = Identity, F = Filter<St, In>> {
62    middleware: M,
63    filter: ServiceChainFactory<F, St, WebRequest<In>>,
64    rdef: Vec<String>,
65    guards: Vec<Box<dyn Guard>>,
66    external: Vec<ResourceDef>,
67    case_insensitive: bool,
68    ph: PhantomData<Out>,
69}
70
71/// A scope with nested services or a configured fallback.
72///
73/// Methods such as [`Scope::service()`], [`Scope::route()`],
74/// [`Scope::configure()`], and [`Scope::default_service()`] turn a [`Scope`]
75/// into `ScopeServices`. You can then add more services or routes and adjust
76/// the scope fallback.
77#[derive(derive_more::Debug)]
78#[debug("ScopeServices({rdef:?})")]
79pub struct ScopeServices<St: State, In, Out, M, F> {
80    middleware: M,
81    rdef: Vec<String>,
82    guards: Vec<Box<dyn Guard>>,
83    filter: ServiceChainFactory<F, St, WebRequest<In>>,
84    services: Vec<Box<dyn AppServiceFactory<St, Out>>>,
85    default: Option<HttpService<St, Out>>,
86    external: Vec<ResourceDef>,
87    case_insensitive: bool,
88}
89
90impl<St: State, In> Scope<St, In, In> {
91    #[allow(clippy::needless_pass_by_value)]
92    /// Create a new scope
93    pub fn new<T: IntoPattern>(path: T) -> Self {
94        Scope {
95            middleware: Identity,
96            filter: factory(Filter::new()),
97            rdef: path.patterns(),
98            guards: Vec::new(),
99            external: Vec::new(),
100            case_insensitive: false,
101            ph: PhantomData,
102        }
103    }
104}
105
106impl<St, In, Out, M, F> Scope<St, In, Out, M, F>
107where
108    St: State,
109    In: 'static,
110    Out: 'static,
111    F: ServiceFactory<
112            St,
113            WebRequest<In>,
114            Res = WebRequest<Out>,
115            Error = WebError<St, St::Error>,
116            InitError = Failure,
117        >,
118{
119    /// Add a match guard to this scope.
120    ///
121    /// The scope is selected only when its path prefix and all registered
122    /// guards match. If a guard rejects the request, the application router can
123    /// try another matching scope or resource; otherwise the application's
124    /// default service is used.
125    ///
126    /// The guard applies to every resource nested in the scope.
127    ///
128    /// ```rust
129    /// use ntex::web::{self, guard, App};
130    ///
131    /// App::default().service(
132    ///     web::scope("/api")
133    ///         .guard(guard::Header("x-api-version", "2"))
134    ///         .route("/users", web::get().to(async || "Version 2 users"))
135    /// );
136    /// ```
137    #[must_use]
138    pub fn guard<G: Guard + 'static>(mut self, guard: G) -> Self {
139        self.guards.push(Box::new(guard));
140        self
141    }
142
143    /// Use ascii case-insensitive routing.
144    ///
145    /// Only static segments could be case-insensitive.
146    #[must_use]
147    pub fn case_insensitive_routing(mut self) -> Self {
148        self.case_insensitive = true;
149        self
150    }
151
152    /// Run external configuration as part of the scope building
153    /// process
154    ///
155    /// This function is useful for moving parts of configuration to a
156    /// different module or even library. For example,
157    /// some of the resource's configuration could be moved to different module.
158    ///
159    /// ```rust,ignore
160    /// use ntex::web::{self, middleware, App, HttpResponse};
161    ///
162    /// // this function could be located in different module
163    /// fn config(cfg: &mut web::ServiceConfig) {
164    ///     cfg.service(web::resource("/test")
165    ///         .route(web::get().to(async || { HttpResponse::Ok() }))
166    ///         .route(web::head().to(async || { HttpResponse::MethodNotAllowed() }))
167    ///     );
168    /// }
169    ///
170    /// fn main() {
171    ///     let app = App::default()
172    ///         .middleware(middleware::Logger::default())
173    ///         .service(
174    ///             web::scope("/api")
175    ///                 .configure(config)
176    ///         )
177    ///         .route("/index.html", web::get().to(async || { HttpResponse::Ok() }));
178    /// }
179    /// ```
180    #[must_use]
181    pub fn configure(
182        self,
183        f: impl FnOnce(&mut ServiceConfig<St, Out>),
184    ) -> ScopeServices<St, In, Out, M, F> {
185        let mut cfg = ServiceConfig::new(self.external);
186        f(&mut cfg);
187
188        ScopeServices {
189            rdef: self.rdef,
190            guards: self.guards,
191            filter: self.filter,
192            middleware: self.middleware,
193            default: None,
194            services: cfg.services,
195            external: cfg.external,
196            case_insensitive: self.case_insensitive,
197        }
198    }
199
200    /// Registers a web service for this scope.
201    ///
202    /// The service's path is joined with the scope prefix. A service can be a
203    /// [`Resource`], another [`Scope`], an attribute-macro handler, or a custom
204    /// service built with `web::service()`.
205    ///
206    /// If this scope matches but none of its services do, the scope's default
207    /// service is used.
208    ///
209    /// ```rust
210    /// use ntex::web::{self, App};
211    ///
212    /// App::default().service(
213    ///     web::scope("/api")
214    ///         .service(web::resource("/users").to(async || "users"))
215    ///         .service(
216    ///             web::scope("/admin")
217    ///                 .route("/health", web::get().to(async || "OK")),
218    ///         ),
219    /// );
220    /// ```
221    #[must_use]
222    pub fn service(
223        self,
224        factory: impl WebServiceFactory<St, Out>,
225    ) -> ScopeServices<St, In, Out, M, F> {
226        ScopeServices {
227            rdef: self.rdef,
228            guards: self.guards,
229            filter: self.filter,
230            middleware: self.middleware,
231            default: None,
232            external: self.external,
233            case_insensitive: self.case_insensitive,
234            services: vec![Box::new(ServiceFactoryWrapper::new(factory))],
235        }
236    }
237
238    /// Register a route for a path relative to this scope.
239    ///
240    /// This is shorthand for creating a [`Resource`] with one route and
241    /// registering it with [`Scope::service()`]. The route's method and custom
242    /// guards are promoted to resource guards.
243    /// A request must match one of the route's methods and every custom guard.
244    ///
245    /// If those guards reject a request, the generated resource does not match
246    /// and the scope router continues searching. If nothing else in the scope
247    /// matches, the scope default service is used. Register an explicit
248    /// [`Resource`] when route mismatches should use a resource-level fallback.
249    ///
250    /// Each call creates a separate resource, so the same relative path can be
251    /// registered more than once with different guards.
252    ///
253    /// ```rust
254    /// use ntex::web::{self, App, HttpResponse};
255    ///
256    /// App::default().service(
257    ///     web::scope("/api")
258    ///         .route("/items", web::get().to(async || "list"))
259    ///         .route(
260    ///             "/items",
261    ///             web::post().to(async || HttpResponse::Created()),
262    ///         )
263    /// );
264    /// ```
265    #[must_use]
266    pub fn route(self, path: &str, mut route: Route<St, Out>) -> ScopeServices<St, In, Out, M, F> {
267        self.service(
268            Resource::new(path)
269                .add_guards(route.take_guards())
270                .route(route),
271        )
272    }
273
274    /// Set the fallback service for unmatched requests within this scope.
275    ///
276    /// The fallback is called after the scope prefix and guards match but no
277    /// nested resource matches. Without a custom fallback, the scope returns
278    /// `404 Not Found`; it does not delegate to the application's fallback.
279    /// Routing failures inside a matched resource are handled by that
280    /// resource's fallback instead.
281    ///
282    /// ```rust
283    /// use ntex::web::{self, App, HttpRequest, HttpResponse};
284    ///
285    /// async fn not_found(req: HttpRequest) -> HttpResponse {
286    ///     HttpResponse::NotFound()
287    ///         .body(format!("No API resource for {}", req.path()))
288    /// }
289    ///
290    /// App::default().service(
291    ///     web::scope("/api")
292    ///         .route("/health", web::get().to(async || "ready"))
293    ///         .default_service(web::to(not_found))
294    /// );
295    /// ```
296    #[must_use]
297    pub fn default_service<Sf>(
298        self,
299        f: impl IntoServiceFactory<Sf, St, WebRequest<Out>>,
300    ) -> ScopeServices<St, In, Out, M, F>
301    where
302        Sf: ServiceFactory<St, WebRequest<Out>, Res = WebResponse> + 'static,
303        Sf::Error: WebResponseError<St, St::Error>,
304        Sf::InitError: IntoFailure,
305    {
306        // create and configure default resource
307        let default = boxed::factory(
308            f.into_factory()
309                .map_err(WebError::from_err)
310                .map_init_err(IntoFailure::fail),
311        );
312
313        ScopeServices {
314            rdef: self.rdef,
315            guards: self.guards,
316            filter: self.filter,
317            middleware: self.middleware,
318            default: Some(default),
319            external: self.external,
320            case_insensitive: self.case_insensitive,
321            services: Vec::new(),
322        }
323    }
324
325    /// Registers a request filter for this scope.
326    ///
327    /// The filter runs after the scope's path and guards match, but before its
328    /// nested router selects a resource. It is not called for requests that do
329    /// not match this scope.
330    ///
331    /// ```rust
332    /// use std::convert::Infallible;
333    /// use ntex::web::{self, App, WebRequest};
334    ///
335    /// async fn user(_state: &(), user_id: usize) -> String {
336    ///     format!("User {user_id}")
337    /// }
338    ///
339    /// App::new().service(
340    ///     web::scope("/api")
341    ///         .filter(async |req: WebRequest<()>| {
342    ///             Ok::<_, Infallible>(req.map_state(|()| 42usize))
343    ///         })
344    ///         .route("/user", web::get().to_with_state(user)),
345    /// );
346    /// ```
347    #[must_use]
348    pub fn filter<U, R>(
349        self,
350        filter: impl IntoServiceFactory<U, St, WebRequest<Out>>,
351    ) -> Scope<
352        St,
353        In,
354        R,
355        M,
356        impl ServiceFactory<
357            St,
358            WebRequest<In>,
359            Res = WebRequest<R>,
360            Error = WebError<St, St::Error>,
361            InitError = Failure,
362        >,
363    >
364    where
365        U: ServiceFactory<St, WebRequest<Out>, Res = WebRequest<R>>,
366        U::Error: WebResponseError<St, St::Error>,
367        U::InitError: IntoFailure,
368    {
369        Scope {
370            filter: self.filter.and_then(
371                filter
372                    .into_factory()
373                    .map_err(WebError::from_err)
374                    .map_init_err(IntoFailure::fail),
375            ),
376            middleware: self.middleware,
377            rdef: self.rdef,
378            guards: self.guards,
379            external: self.external,
380            case_insensitive: self.case_insensitive,
381            ph: PhantomData,
382        }
383    }
384
385    /// Registers a middleware for this scope.
386    ///
387    /// The middleware runs only after the scope's path and guards match. It
388    /// wraps everything inside the scope, including its filter, nested routes,
389    /// and fallback service. This means it can inspect or modify both the
390    /// request and response, even when no nested route matches.
391    ///
392    /// ```rust
393    /// use ntex::web::{self, middleware, App};
394    ///
395    /// App::default().service(
396    ///     web::scope("/api")
397    ///         .middleware(
398    ///             middleware::DefaultHeaders::new()
399    ///                 .header("x-api", "v1"),
400    ///         )
401    ///         .route("/health", web::get().to(async || "OK")),
402    /// );
403    /// ```
404    #[must_use]
405    #[doc(alias = "wrap")]
406    pub fn middleware<U>(self, mw: U) -> Scope<St, In, Out, WebStack<St, U, M>, F> {
407        Scope {
408            middleware: WebStack::new(mw, self.middleware),
409            filter: self.filter,
410            rdef: self.rdef,
411            guards: self.guards,
412            external: self.external,
413            case_insensitive: self.case_insensitive,
414            ph: PhantomData,
415        }
416    }
417}
418
419impl<St, In, Out, M, F> ScopeServices<St, In, Out, M, F>
420where
421    St: State,
422    In: 'static,
423    Out: 'static,
424    F: ServiceFactory<
425            St,
426            WebRequest<In>,
427            Res = WebRequest<Out>,
428            Error = WebError<St, St::Error>,
429            InitError = Failure,
430        >,
431{
432    /// Registers another web service inside this scope.
433    ///
434    /// This has the same behavior as [`Scope::service()`]. The service's path
435    /// is joined with the scope prefix and added to the scope's nested router.
436    ///
437    /// If no nested service matches, the scope's default service is used.
438    #[must_use]
439    pub fn service(mut self, factory: impl WebServiceFactory<St, Out>) -> Self {
440        self.services
441            .push(Box::new(ServiceFactoryWrapper::new(factory)));
442        self
443    }
444
445    /// Register a route for a path relative to this scope.
446    ///
447    /// This is shorthand for creating a [`Resource`] with one route and
448    /// registering it with [`ScopeServices::service()`]. The route's method and
449    /// custom guards are promoted to resource guards.
450    /// A request must match one of the route's methods and every custom guard.
451    ///
452    /// Each call creates a separate resource, so the same relative path can be
453    /// registered more than once with different guards.
454    ///
455    /// ```rust
456    /// use ntex::web::{self, App, HttpResponse};
457    ///
458    /// App::default().service(
459    ///     web::scope("/api")
460    ///         .route("/items", web::get().to(async || "list"))
461    ///         .route(
462    ///             "/items",
463    ///             web::post().to(async || HttpResponse::Created()),
464    ///         )
465    /// );
466    /// ```
467    #[must_use]
468    pub fn route(self, path: &str, mut route: Route<St, Out>) -> Self {
469        self.service(
470            Resource::new(path)
471                .add_guards(route.take_guards())
472                .route(route),
473        )
474    }
475
476    /// Set the fallback service for unmatched requests within this scope.
477    ///
478    /// The fallback is called after the scope prefix and guards match but no
479    /// nested resource matches. Without a custom fallback, the scope returns
480    /// `404 Not Found`; it does not delegate to the application's fallback.
481    /// Routing failures inside a matched resource are handled by that
482    /// resource's fallback instead.
483    ///
484    /// ```rust
485    /// use ntex::web::{self, App, HttpRequest, HttpResponse};
486    ///
487    /// async fn not_found(req: HttpRequest) -> HttpResponse {
488    ///     HttpResponse::NotFound()
489    ///         .body(format!("No API resource for {}", req.path()))
490    /// }
491    ///
492    /// App::default().service(
493    ///     web::scope("/api")
494    ///         .route("/health", web::get().to(async || "ready"))
495    ///         .default_service(web::to(not_found))
496    /// );
497    /// ```
498    #[must_use]
499    pub fn default_service<Sf>(
500        mut self,
501        f: impl IntoServiceFactory<Sf, St, WebRequest<Out>>,
502    ) -> Self
503    where
504        Sf: ServiceFactory<St, WebRequest<Out>, Res = WebResponse> + 'static,
505        Sf::Error: WebResponseError<St, St::Error>,
506        Sf::InitError: IntoFailure,
507    {
508        // create and configure default resource
509        self.default = Some(boxed::factory(
510            f.into_factory()
511                .map_err(WebError::from_err)
512                .map_init_err(IntoFailure::fail),
513        ));
514
515        self
516    }
517}
518
519impl<St, Outer, In, Out, M, F> WebServiceFactory<St, Outer> for ScopeServices<St, In, Out, M, F>
520where
521    St: State,
522    Outer: 'static,
523    In: 'static,
524    Out: 'static,
525    F: ServiceFactory<
526            St,
527            WebRequest<In>,
528            Res = WebRequest<Out>,
529            Error = WebError<St, St::Error>,
530            InitError = Failure,
531        > + 'static,
532    M: Middleware<WebServiceRouter<St, In, Out, F::Service>, St> + 'static,
533    M::Service: Service<St, WebRequest<Outer>, Res = WebResponse, Error = WebError<St, St::Error>>,
534{
535    fn register(mut self, config: &mut WebServiceConfig<St, Outer>) {
536        // Default service
537        let default = self.default.unwrap_or_else(|| {
538            boxed::factory(
539                factory(async move |req: WebRequest<Out>| {
540                    Ok(req.into_response(Response::NotFound().build()))
541                })
542                .map_init_err(|_| unreachable!()),
543            )
544        });
545
546        // Web app config
547        let mut cfg = WebServiceConfig::new();
548
549        // register nested services
550        for mut svc in self.services {
551            svc.register(&mut cfg);
552        }
553
554        // ResourceMap tree
555        let slash = self.rdef.iter().any(|s| s.ends_with('/'));
556        let mut rmap = ResourceMap::new(ResourceDef::root_prefix(self.rdef.clone()));
557
558        for mut rdef in std::mem::take(&mut self.external) {
559            rmap.add(&mut rdef, None);
560        }
561
562        // Complete scope pipeline creation
563        let services: Vec<_> = cfg
564            .into_services()
565            .into_iter()
566            .map(|(rdef, srv, guards, nested)| {
567                // case for scope prefix ends with '/' and
568                // resource is empty pattern
569                let mut rdef = if slash && rdef.pattern() == "" {
570                    ResourceDef::new("/")
571                } else {
572                    rdef
573                };
574                rmap.add(&mut rdef, nested);
575                (rdef, srv, RefCell::new(guards))
576            })
577            .collect();
578
579        // Create router
580        let mut router = Router::builder();
581        if self.case_insensitive {
582            router.case_insensitive();
583        }
584        for (path, factory, guards) in services {
585            router
586                .resource(path.clone(), factory)
587                .set_check_value(guards.borrow_mut().take());
588        }
589
590        // register final service
591        config.register_service(
592            ResourceDef::root_prefix(self.rdef),
593            if self.guards.is_empty() {
594                None
595            } else {
596                Some(self.guards)
597            },
598            Some(Rc::new(rmap)),
599            ScopeServiceFactory {
600                default,
601                middleware: self.middleware,
602                filter: self.filter,
603                router: Rc::new(router.build()),
604            },
605        );
606    }
607}
608
609/// Scope service
610struct ScopeServiceFactory<St: State, In, Out, M, F> {
611    middleware: M,
612    filter: ServiceChainFactory<F, St, WebRequest<In>>,
613    router: Rc<Router<WebRoute<St, Out>, Guards>>,
614    default: HttpService<St, Out>,
615}
616
617impl<St, Outer, In, Out, M, F> ServiceFactory<St, WebRequest<Outer>>
618    for ScopeServiceFactory<St, In, Out, M, F>
619where
620    St: State,
621    Outer: 'static,
622    In: 'static,
623    Out: 'static,
624    F: ServiceFactory<
625            St,
626            WebRequest<In>,
627            Res = WebRequest<Out>,
628            Error = WebError<St, St::Error>,
629            InitError = Failure,
630        > + 'static,
631    M: Middleware<WebServiceRouter<St, In, Out, F::Service>, St> + 'static,
632    M::Service: Service<St, WebRequest<Outer>, Res = WebResponse, Error = WebError<St, St::Error>>,
633{
634    type Res = WebResponse;
635    type Error = WebError<St, St::Error>;
636
637    type Service = M::Service;
638    type InitError = Failure;
639
640    async fn create(&self, st: &St) -> Result<Self::Service, Self::InitError> {
641        let filter = self.filter.create(st).await?;
642
643        // router service
644        Ok(self.middleware.create(
645            st,
646            WebServiceRouter::new(
647                filter,
648                Filter::<St, In>::is_identity::<F>(),
649                self.router.clone(),
650                self.default.clone(),
651            ),
652        ))
653    }
654}
655
656#[cfg(test)]
657mod tests {
658    use std::convert::Infallible;
659
660    use crate::http::body::{Body, ResponseBody};
661    use crate::http::header::{CONTENT_TYPE, HeaderValue};
662    use crate::http::{Method, StatusCode};
663    use crate::util::Bytes;
664    use crate::web::middleware::DefaultHeaders;
665    use crate::web::test::{TestRequest, call_service, init_service, read_body};
666    use crate::web::{self, App, HttpRequest, HttpResponse, WebRequest, guard};
667
668    /// STATEMENT: Scopes match complete resource paths and can enable case-insensitive child routing.
669    ///
670    /// HOW:
671    /// - Register normal and case-insensitive scopes serving `/path1`.
672    /// - Assert exact paths succeed, `/path10` misses, and `/Path1` succeeds in the latter scope.
673    #[crate::rt_test]
674    async fn test_scope() {
675        let srv = init_service(
676            App::new()
677                .service(
678                    web::scope("/app")
679                        .service(web::resource("/path1").to(async || HttpResponse::Ok())),
680                )
681                .service(
682                    web::scope("/app2")
683                        .case_insensitive_routing()
684                        .service(web::resource("/path1").to(async || HttpResponse::Ok())),
685                ),
686        )
687        .await;
688
689        let req = TestRequest::with_uri("/app/path1").to_request();
690        let resp = srv.call(req).await.unwrap();
691        assert_eq!(resp.status(), StatusCode::OK);
692
693        let req = TestRequest::with_uri("/app/path10").to_request();
694        let resp = srv.call(req).await.unwrap();
695        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
696
697        let req = TestRequest::with_uri("/app2/path1").to_request();
698        let resp = srv.call(req).await.unwrap();
699        assert_eq!(resp.status(), StatusCode::OK);
700
701        let req = TestRequest::with_uri("/app2/Path1").to_request();
702        let resp = srv.call(req).await.unwrap();
703        assert_eq!(resp.status(), StatusCode::OK);
704    }
705
706    /// STATEMENT: Empty and slash resources distinguish the two forms of a scope root.
707    ///
708    /// HOW:
709    /// - Register separate handlers for `""` and `/` under `/app`.
710    /// - Assert `/app` returns OK and `/app/` returns `CREATED`.
711    #[crate::rt_test]
712    async fn test_scope_root() {
713        let srv = init_service(
714            App::new().service(
715                web::scope("/app")
716                    .service(web::resource("").to(async || HttpResponse::Ok()))
717                    .service(web::resource("/").to(async || HttpResponse::Created())),
718            ),
719        )
720        .await;
721
722        let req = TestRequest::with_uri("/app").to_request();
723        let resp = srv.call(req).await.unwrap();
724        assert_eq!(resp.status(), StatusCode::OK);
725
726        let req = TestRequest::with_uri("/app/").to_request();
727        let resp = srv.call(req).await.unwrap();
728        assert_eq!(resp.status(), StatusCode::CREATED);
729    }
730
731    /// STATEMENT: Every prefix in a multi-pattern scope preserves empty-versus-slash root matching.
732    ///
733    /// HOW:
734    /// - Register empty and slash resources under both `/app` and `/app2`.
735    /// - Assert roots without slashes return OK and roots with slashes return `CREATED`.
736    #[crate::rt_test]
737    async fn test_scope_root_multi() {
738        let srv = init_service(
739            App::new().service(
740                web::scope(["/app", "/app2"])
741                    .service(web::resource("").to(async || HttpResponse::Ok()))
742                    .service(web::resource("/").to(async || HttpResponse::Created())),
743            ),
744        )
745        .await;
746
747        for url in &["/app", "/app2"] {
748            let req = TestRequest::with_uri(url).to_request();
749            let resp = srv.call(req).await.unwrap();
750            assert_eq!(resp.status(), StatusCode::OK);
751        }
752
753        for url in &["/app/", "/app2/"] {
754            let req = TestRequest::with_uri(url).to_request();
755            let resp = srv.call(req).await.unwrap();
756            assert_eq!(resp.status(), StatusCode::CREATED);
757        }
758    }
759
760    /// STATEMENT: An empty resource under a slash-terminated scope requires the trailing slash.
761    ///
762    /// HOW:
763    /// - Mount an empty resource under `/app/`.
764    /// - Assert `/app` returns 404 and `/app/` returns OK.
765    #[crate::rt_test]
766    async fn test_scope_root2() {
767        let srv = init_service(App::new().service(
768            web::scope("/app/").service(web::resource("").to(async || HttpResponse::Ok())),
769        ))
770        .await;
771
772        let req = TestRequest::with_uri("/app").to_request();
773        let resp = srv.call(req).await.unwrap();
774        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
775
776        let req = TestRequest::with_uri("/app/").to_request();
777        let resp = srv.call(req).await.unwrap();
778        assert_eq!(resp.status(), StatusCode::OK);
779    }
780
781    /// STATEMENT: Slash-terminated multi-pattern scopes require slashes for their empty resource.
782    ///
783    /// HOW:
784    /// - Mount an empty resource under `/app/` and `/app2/`.
785    /// - Assert both unsuffixed roots return 404 and both slash-suffixed roots return OK.
786    #[crate::rt_test]
787    async fn test_scope_root2_multi() {
788        let srv = init_service(
789            App::new().service(
790                web::scope(["/app/", "/app2/"])
791                    .service(web::resource("").to(async || HttpResponse::Ok())),
792            ),
793        )
794        .await;
795
796        for url in &["/app", "/app2"] {
797            let req = TestRequest::with_uri(url).to_request();
798            let resp = srv.call(req).await.unwrap();
799            assert_eq!(resp.status(), StatusCode::NOT_FOUND);
800        }
801
802        for url in &["/app/", "/app2/"] {
803            let req = TestRequest::with_uri(url).to_request();
804            let resp = srv.call(req).await.unwrap();
805            assert_eq!(resp.status(), StatusCode::OK);
806        }
807    }
808
809    /// STATEMENT: A slash resource under a slash-terminated scope matches its single-slash root.
810    ///
811    /// HOW:
812    /// - Register `/` within `/app/`.
813    /// - Assert `/app` returns 404 while `/app/` returns OK.
814    #[crate::rt_test]
815    async fn test_scope_root3() {
816        let srv = init_service(App::new().service(
817            web::scope("/app/").service(web::resource("/").to(async || HttpResponse::Ok())),
818        ))
819        .await;
820
821        let req = TestRequest::with_uri("/app").to_request();
822        let resp = srv.call(req).await.unwrap();
823        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
824
825        let req = TestRequest::with_uri("/app/").to_request();
826        let resp = srv.call(req).await.unwrap();
827        assert_eq!(resp.status(), StatusCode::OK);
828    }
829
830    /// STATEMENT: Direct scope routes dispatch matching methods and leave unmatched methods unhandled.
831    ///
832    /// HOW:
833    /// - Register GET and DELETE at `/path1` under the slashless prefix `app`.
834    /// - Assert GET and DELETE return OK while POST returns 404 at `/app/path1`.
835    #[crate::rt_test]
836    async fn test_scope_route() {
837        let srv = init_service(
838            App::new().service(
839                web::scope("app")
840                    .route("/path1", web::get().to(async || HttpResponse::Ok()))
841                    .route("/path1", web::delete().to(async || HttpResponse::Ok())),
842            ),
843        )
844        .await;
845
846        for (m, status) in &[
847            (Method::GET, StatusCode::OK),
848            (Method::DELETE, StatusCode::OK),
849            (Method::POST, StatusCode::NOT_FOUND),
850        ] {
851            let req = TestRequest::with_uri("/app/path1")
852                .method(m.clone())
853                .to_request();
854            let resp = srv.call(req).await.unwrap();
855            assert_eq!(resp.status(), status.clone());
856        }
857    }
858
859    /// STATEMENT: Direct routes work identically across every prefix of a multi-pattern scope.
860    ///
861    /// HOW:
862    /// - Register GET and DELETE routes under `app` and `app2`.
863    /// - Request both prefixes with GET, DELETE, and POST and assert OK, OK, and 404.
864    #[crate::rt_test]
865    async fn test_scope_route_multi() {
866        let srv = init_service(
867            App::new().service(
868                web::scope(["app", "app2"])
869                    .route("/path1", web::get().to(async || HttpResponse::Ok()))
870                    .route("/path1", web::delete().to(async || HttpResponse::Ok())),
871            ),
872        )
873        .await;
874
875        for (m, status) in &[
876            (Method::GET, StatusCode::OK),
877            (Method::DELETE, StatusCode::OK),
878            (Method::POST, StatusCode::NOT_FOUND),
879        ] {
880            let req = TestRequest::with_uri("/app/path1")
881                .method(m.clone())
882                .to_request();
883            let resp = srv.call(req).await.unwrap();
884            assert_eq!(resp.status(), status.clone());
885
886            let req = TestRequest::with_uri("/app2/path1")
887                .method(m.clone())
888                .to_request();
889            let resp = srv.call(req).await.unwrap();
890            assert_eq!(resp.status(), status.clone());
891        }
892    }
893
894    /// STATEMENT: Scope and resource patterns without leading slashes compose into a normal path.
895    ///
896    /// HOW:
897    /// - Register resource `path1` under scope `app` with GET and DELETE handlers.
898    /// - Assert `/app/path1` returns OK for those methods and 405 for POST.
899    #[crate::rt_test]
900    async fn test_scope_route_without_leading_slash() {
901        let srv = init_service(
902            App::new().service(
903                web::scope("app").service(
904                    web::resource("path1")
905                        .route(web::get().to(async || HttpResponse::Ok()))
906                        .route(web::delete().to(async || HttpResponse::Ok())),
907                ),
908            ),
909        )
910        .await;
911
912        let req = TestRequest::with_uri("/app/path1").to_request();
913        let resp = srv.call(req).await.unwrap();
914        assert_eq!(resp.status(), StatusCode::OK);
915
916        let req = TestRequest::with_uri("/app/path1")
917            .method(Method::DELETE)
918            .to_request();
919        let resp = srv.call(req).await.unwrap();
920        assert_eq!(resp.status(), StatusCode::OK);
921
922        let req = TestRequest::with_uri("/app/path1")
923            .method(Method::POST)
924            .to_request();
925        let resp = srv.call(req).await.unwrap();
926        assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
927    }
928
929    /// STATEMENT: Scope guards select matching scopes and allow other resources to handle misses.
930    ///
931    /// HOW:
932    /// - Register GET- and POST-guarded scopes sharing `/app`, followed by an unguarded resource.
933    /// - Assert POST returns 304, GET returns OK, and DELETE reaches the fallback resource's 204.
934    #[crate::rt_test]
935    async fn test_scope_guard() {
936        let srv = init_service(
937            App::new()
938                .service(
939                    web::scope("/app")
940                        .guard(guard::Get())
941                        .service(web::resource("/path1").to(async || HttpResponse::Ok())),
942                )
943                .service(
944                    web::scope("/app")
945                        .guard(guard::Post())
946                        .service(web::resource("/path1").to(async || HttpResponse::NotModified())),
947                )
948                .service(web::resource("/app/path1").to(async || HttpResponse::NoContent())),
949        )
950        .await;
951
952        let req = TestRequest::with_uri("/app/path1")
953            .method(Method::POST)
954            .to_request();
955        let resp = srv.call(req).await.unwrap();
956        assert_eq!(resp.status(), StatusCode::NOT_MODIFIED);
957
958        let req = TestRequest::with_uri("/app/path1")
959            .method(Method::GET)
960            .to_request();
961        let resp = srv.call(req).await.unwrap();
962        assert_eq!(resp.status(), StatusCode::OK);
963
964        let req = TestRequest::with_uri("/app/path1")
965            .method(Method::DELETE)
966            .to_request();
967        let resp = srv.call(req).await.unwrap();
968        assert_eq!(resp.status(), StatusCode::NO_CONTENT);
969    }
970
971    /// STATEMENT: A variable embedded in a scope segment is available to its child handler.
972    ///
973    /// HOW:
974    /// - Serve `/path1` under `/ab-{project}` and request a matching project path.
975    /// - Assert OK and the project text when the body is bytes; assert a different prefix returns 404.
976    #[crate::rt_test]
977    async fn test_scope_variable_segment() {
978        let srv = init_service(App::new().service(web::scope("/ab-{project}").service(
979            web::resource("/path1").to(async move |r: HttpRequest| {
980                HttpResponse::Ok().body(format!("project: {}", &r.match_info()["project"]))
981            }),
982        )))
983        .await;
984
985        let req = TestRequest::with_uri("/ab-project1/path1").to_request();
986        let resp = srv.call(req).await.unwrap();
987        assert_eq!(resp.status(), StatusCode::OK);
988
989        if let ResponseBody::Body(Body::Bytes(b)) = resp.body() {
990            let bytes: Bytes = b.clone();
991            assert_eq!(bytes, Bytes::from_static(b"project: project1"));
992        }
993
994        let req = TestRequest::with_uri("/aa-project1/path1").to_request();
995        let resp = srv.call(req).await.unwrap();
996        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
997    }
998
999    /// STATEMENT: Variable scope roots support empty and slash resource patterns.
1000    ///
1001    /// HOW:
1002    /// - Register both root patterns under `/ab-{project}` and request both root spellings.
1003    /// - Assert OK and captured project text for byte bodies, then assert a mismatched prefix returns 404.
1004    #[crate::rt_test]
1005    async fn test_scope_variable_segment2() {
1006        let srv = init_service(App::new().service(web::scope("/ab-{project}").service(
1007            web::resource(["", "/"]).to(async move |r: HttpRequest| {
1008                HttpResponse::Ok().body(format!("project: {}", &r.match_info()["project"]))
1009            }),
1010        )))
1011        .await;
1012
1013        let req = TestRequest::with_uri("/ab-project1").to_request();
1014        let resp = srv.call(req).await.unwrap();
1015        assert_eq!(resp.status(), StatusCode::OK);
1016
1017        if let ResponseBody::Body(Body::Bytes(b)) = resp.body() {
1018            let bytes: Bytes = b.clone();
1019            assert_eq!(bytes, Bytes::from_static(b"project: project1"));
1020        }
1021
1022        let req = TestRequest::with_uri("/ab-project1/").to_request();
1023        let resp = srv.call(req).await.unwrap();
1024        assert_eq!(resp.status(), StatusCode::OK);
1025
1026        if let ResponseBody::Body(Body::Bytes(b)) = resp.body() {
1027            let bytes: Bytes = b.clone();
1028            assert_eq!(bytes, Bytes::from_static(b"project: project1"));
1029        }
1030
1031        let req = TestRequest::with_uri("/aa-project1").to_request();
1032        let resp = srv.call(req).await.unwrap();
1033        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
1034    }
1035
1036    /// STATEMENT: Nested scopes compose their prefixes with child resource paths.
1037    ///
1038    /// HOW:
1039    /// - Nest `/t1` under `/app` and register a `/path1` handler returning `Created`.
1040    /// - Request `/app/t1/path1` and assert status 201.
1041    #[crate::rt_test]
1042    async fn test_nested_scope() {
1043        let srv = init_service(App::new().service(web::scope("/app").service(
1044            web::scope("/t1").service(web::resource("/path1").to(async || HttpResponse::Created())),
1045        )))
1046        .await;
1047
1048        let req = TestRequest::with_uri("/app/t1/path1").to_request();
1049        let resp = srv.call(req).await.unwrap();
1050        assert_eq!(resp.status(), StatusCode::CREATED);
1051    }
1052
1053    /// STATEMENT: A nested scope without a leading slash still composes with its parent prefix.
1054    ///
1055    /// HOW:
1056    /// - Nest `t1` under `/app` and register `/path1`.
1057    /// - Request `/app/t1/path1` and assert the handler's `CREATED` response.
1058    #[crate::rt_test]
1059    async fn test_nested_scope_no_slash() {
1060        let srv = init_service(App::new().service(web::scope("/app").service(
1061            web::scope("t1").service(web::resource("/path1").to(async || HttpResponse::Created())),
1062        )))
1063        .await;
1064
1065        let req = TestRequest::with_uri("/app/t1/path1").to_request();
1066        let resp = srv.call(req).await.unwrap();
1067        assert_eq!(resp.status(), StatusCode::CREATED);
1068    }
1069
1070    /// STATEMENT: Nested scopes preserve the distinction between empty and slash root resources.
1071    ///
1072    /// HOW:
1073    /// - Register distinct empty and slash handlers under `/app/t1`.
1074    /// - Assert `/app/t1` returns OK and `/app/t1/` returns `CREATED`.
1075    #[crate::rt_test]
1076    async fn test_nested_scope_root() {
1077        let srv = init_service(
1078            App::new().service(
1079                web::scope("/app").service(
1080                    web::scope("/t1")
1081                        .service(web::resource("").to(async || HttpResponse::Ok()))
1082                        .service(web::resource("/").to(async || HttpResponse::Created())),
1083                ),
1084            ),
1085        )
1086        .await;
1087
1088        let req = TestRequest::with_uri("/app/t1").to_request();
1089        let resp = srv.call(req).await.unwrap();
1090        assert_eq!(resp.status(), StatusCode::OK);
1091
1092        let req = TestRequest::with_uri("/app/t1/").to_request();
1093        let resp = srv.call(req).await.unwrap();
1094        assert_eq!(resp.status(), StatusCode::CREATED);
1095    }
1096
1097    /// STATEMENT: Method guards on nested scopes reject nonmatching requests before child routing.
1098    ///
1099    /// HOW:
1100    /// - Guard `/app/t1` with `Get` and register `/path1`.
1101    /// - Assert POST returns 404 and GET reaches the child handler with OK.
1102    #[crate::rt_test]
1103    async fn test_nested_scope_filter() {
1104        let srv = init_service(
1105            App::new().service(
1106                web::scope("/app").service(
1107                    web::scope("/t1")
1108                        .guard(guard::Get())
1109                        .service(web::resource("/path1").to(async || HttpResponse::Ok())),
1110                ),
1111            ),
1112        )
1113        .await;
1114
1115        let req = TestRequest::with_uri("/app/t1/path1")
1116            .method(Method::POST)
1117            .to_request();
1118        let resp = srv.call(req).await.unwrap();
1119        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
1120
1121        let req = TestRequest::with_uri("/app/t1/path1")
1122            .method(Method::GET)
1123            .to_request();
1124        let resp = srv.call(req).await.unwrap();
1125        assert_eq!(resp.status(), StatusCode::OK);
1126    }
1127
1128    /// STATEMENT: A nested variable scope exposes its captured segment to the child handler.
1129    ///
1130    /// HOW:
1131    /// - Register `/app/{project_id}/path1` and return the captured project ID.
1132    /// - Assert status 201 and, for a byte body, the expected `project_1` text.
1133    #[crate::rt_test]
1134    async fn test_nested_scope_with_variable_segment() {
1135        let srv = init_service(App::new().service(web::scope("/app").service(
1136            web::scope("/{project_id}").service(web::resource("/path1").to(
1137                async move |r: HttpRequest| {
1138                    HttpResponse::Created()
1139                        .body(format!("project: {}", &r.match_info()["project_id"]))
1140                },
1141            )),
1142        )))
1143        .await;
1144
1145        let req = TestRequest::with_uri("/app/project_1/path1").to_request();
1146        let resp = srv.call(req).await.unwrap();
1147        assert_eq!(resp.status(), StatusCode::CREATED);
1148
1149        if let ResponseBody::Body(Body::Bytes(b)) = resp.body() {
1150            let bytes: Bytes = b.clone();
1151            assert_eq!(bytes, Bytes::from_static(b"project: project_1"));
1152        }
1153    }
1154
1155    /// STATEMENT: Multiple nested variable scopes retain all captures and still enforce child paths.
1156    ///
1157    /// HOW:
1158    /// - Serve `/path1` under `/app/{project}/{id}` and return both captures.
1159    /// - Assert 201 and expected byte-body text for `/app/test/1/path1`, and 404 for `/path2`.
1160    #[crate::rt_test]
1161    async fn test_nested2_scope_with_variable_segment() {
1162        let srv = init_service(App::new().service(web::scope("/app").service(
1163            web::scope("/{project}").service(web::scope("/{id}").service(
1164                web::resource("/path1").to(async move |r: HttpRequest| {
1165                    HttpResponse::Created().body(format!(
1166                        "project: {} - {}",
1167                        &r.match_info()["project"],
1168                        &r.match_info()["id"],
1169                    ))
1170                }),
1171            )),
1172        )))
1173        .await;
1174
1175        let req = TestRequest::with_uri("/app/test/1/path1").to_request();
1176        let resp = srv.call(req).await.unwrap();
1177        assert_eq!(resp.status(), StatusCode::CREATED);
1178
1179        if let ResponseBody::Body(Body::Bytes(b)) = resp.body() {
1180            let bytes: Bytes = b.clone();
1181            assert_eq!(bytes, Bytes::from_static(b"project: test - 1"));
1182        }
1183
1184        let req = TestRequest::with_uri("/app/test/1/path2").to_request();
1185        let resp = srv.call(req).await.unwrap();
1186        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
1187    }
1188
1189    /// STATEMENT: A scope default service handles only requests inside its prefix.
1190    ///
1191    /// HOW:
1192    /// - Register a default service returning `BadRequest` inside `/app`.
1193    /// - Assert an unknown scoped path returns 400 and the same unscoped path returns 404.
1194    #[crate::rt_test]
1195    async fn test_default_resource() {
1196        let srv = init_service(
1197            App::new().service(
1198                web::scope("/app")
1199                    .service(web::resource("/path1").to(async || HttpResponse::Ok()))
1200                    .default_service(async move |r: WebRequest<()>| {
1201                        Ok::<_, Infallible>(r.into_response(HttpResponse::BadRequest()))
1202                    }),
1203            ),
1204        )
1205        .await;
1206
1207        let req = TestRequest::with_uri("/app/path2").to_request();
1208        let resp = srv.call(req).await.unwrap();
1209        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
1210
1211        let req = TestRequest::with_uri("/path2").to_request();
1212        let resp = srv.call(req).await.unwrap();
1213        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
1214    }
1215
1216    /// STATEMENT: Scope filters run before their matching child route.
1217    ///
1218    /// HOW:
1219    /// - Install a flag-setting filter under `app` and register `/test`.
1220    /// - Request `/app/test` and assert OK and that the filter flag was set.
1221    #[crate::rt_test]
1222    async fn test_filter() {
1223        let filter = std::rc::Rc::new(std::cell::Cell::new(false));
1224        let filter2 = filter.clone();
1225        let srv = init_service(
1226            App::new().service(
1227                web::scope("app")
1228                    .filter(async move |req: WebRequest<()>| {
1229                        filter2.set(true);
1230                        Ok::<_, Infallible>(req)
1231                    })
1232                    .route("/test", web::get().to(async || HttpResponse::Ok())),
1233            ),
1234        )
1235        .await;
1236        let req = TestRequest::with_uri("/app/test").to_request();
1237        let resp = call_service(&srv, req).await;
1238        assert_eq!(resp.status(), StatusCode::OK);
1239        assert!(filter.get());
1240    }
1241
1242    /// STATEMENT: Scope middleware applies default headers to child-resource responses.
1243    ///
1244    /// HOW:
1245    /// - Add `DefaultHeaders` with content type `0001` to a scope serving `/test`.
1246    /// - Request `/app/test` and assert OK and the configured header value.
1247    #[crate::rt_test]
1248    async fn test_middleware() {
1249        let srv = init_service(
1250            App::new().service(
1251                web::scope("app")
1252                    .middleware(
1253                        DefaultHeaders::new()
1254                            .header(CONTENT_TYPE, HeaderValue::from_static("0001")),
1255                    )
1256                    .service(
1257                        web::resource("/test").route(web::get().to(async || HttpResponse::Ok())),
1258                    ),
1259            ),
1260        )
1261        .await;
1262
1263        let req = TestRequest::with_uri("/app/test").to_request();
1264        let resp = call_service(&srv, req).await;
1265        assert_eq!(resp.status(), StatusCode::OK);
1266        assert_eq!(
1267            resp.headers().get(CONTENT_TYPE).unwrap(),
1268            HeaderValue::from_static("0001")
1269        );
1270    }
1271
1272    /// STATEMENT: Nested `configure` calls register routes under their enclosing scope prefixes.
1273    ///
1274    /// HOW:
1275    /// - Configure `/app`, then configure `/v1` within it and register `/`.
1276    /// - Request `/app/v1/` and assert OK.
1277    #[crate::rt_test]
1278    async fn test_scope_config_2() {
1279        let srv = init_service(App::new().service(web::scope("/app").configure(|s| {
1280            s.service(web::scope("/v1").configure(|s| {
1281                s.route("/", web::get().to(async || HttpResponse::Ok()));
1282            }));
1283        })))
1284        .await;
1285
1286        let req = TestRequest::with_uri("/app/v1/").to_request();
1287        let resp = srv.call(req).await.unwrap();
1288        assert_eq!(resp.status(), StatusCode::OK);
1289    }
1290
1291    /// STATEMENT: External resources configured inside nested scopes retain their external origin.
1292    ///
1293    /// HOW:
1294    /// - Register the `youtube` external resource in `/app/v1` and return its generated URL from the root handler.
1295    /// - Assert OK and the exact external URL without either scope prefix.
1296    #[crate::rt_test]
1297    async fn test_url_for_external() {
1298        let srv = init_service(App::new().service(web::scope("/app").configure(|s| {
1299            s.service(web::scope("/v1").configure(|s| {
1300                s.external_resource("youtube", "https://youtube.com/watch/{video_id}");
1301                s.route(
1302                    "/",
1303                    web::get().to(async move |req: HttpRequest| {
1304                        HttpResponse::Ok().body(
1305                            req.url_for("youtube", ["xxxxxx"])
1306                                .unwrap()
1307                                .as_str()
1308                                .to_string(),
1309                        )
1310                    }),
1311                );
1312            }));
1313        })))
1314        .await;
1315
1316        let req = TestRequest::with_uri("/app/v1/").to_request();
1317        let resp = srv.call(req).await.unwrap();
1318        assert_eq!(resp.status(), StatusCode::OK);
1319        let body = read_body(resp).await;
1320        assert_eq!(body, &b"https://youtube.com/watch/xxxxxx"[..]);
1321    }
1322
1323    /// STATEMENT: Named nested resources generate URLs including every enclosing scope prefix.
1324    ///
1325    /// HOW:
1326    /// - Name `/a/b/c/{stuff}` as `c` and generate its URL with a replacement value.
1327    /// - Request the handler and assert OK and the full `/a/b/c/12345` absolute URL body.
1328    #[crate::rt_test]
1329    async fn test_url_for_nested() {
1330        let srv = init_service(App::new().service(web::scope("/a").service(
1331            web::scope("/b").service(web::resource("/c/{stuff}").name("c").route(web::get().to(
1332                async move |req: HttpRequest| {
1333                    HttpResponse::Ok().body(format!("{}", req.url_for("c", ["12345"]).unwrap()))
1334                },
1335            ))),
1336        )))
1337        .await;
1338
1339        let req = TestRequest::with_uri("/a/b/c/test").to_request();
1340        let resp = call_service(&srv, req).await;
1341        assert_eq!(resp.status(), StatusCode::OK);
1342        let body = read_body(resp).await;
1343        assert_eq!(
1344            body,
1345            Bytes::from_static(b"http://localhost:8080/a/b/c/12345")
1346        );
1347    }
1348
1349    /// STATEMENT: Nested handlers resolve parent, external, and sibling resource names correctly.
1350    ///
1351    /// HOW:
1352    /// - Register root and sibling resources plus an external URL and expose them from two nesting levels.
1353    /// - Request `/a/` and `/a/b/` and assert OK and identical correctly prefixed URL bodies.
1354    #[crate::rt_test]
1355    async fn test_url_for_parent() {
1356        async fn urls(req: HttpRequest) -> HttpResponse {
1357            let index = req.url_for("index", ["1"]).unwrap();
1358            let youtube = req.url_for("youtube", ["2"]).unwrap();
1359            let sibling = req.url_for("sibling", ["3"]).unwrap();
1360            HttpResponse::Ok().body(format!("{index} {youtube} {sibling}"))
1361        }
1362
1363        let srv = init_service(
1364            App::new()
1365                .external_resource("youtube", "https://youtube.com/watch/{video_id}")
1366                .service(
1367                    web::resource("/index/{id}")
1368                        .name("index")
1369                        .to(async || HttpResponse::Ok()),
1370                )
1371                .service(
1372                    web::scope("/sibling").service(
1373                        web::resource("/{id}")
1374                            .name("sibling")
1375                            .to(async || HttpResponse::Ok()),
1376                    ),
1377                )
1378                .service(
1379                    web::scope("/a")
1380                        .service(web::resource("/").to(urls))
1381                        .service(web::scope("/b").service(web::resource("/").to(urls))),
1382                ),
1383        )
1384        .await;
1385
1386        for uri in ["/a/", "/a/b/"] {
1387            let req = TestRequest::with_uri(uri).to_request();
1388            let resp = call_service(&srv, req).await;
1389            assert_eq!(resp.status(), StatusCode::OK);
1390            let body = read_body(resp).await;
1391            assert_eq!(
1392                body,
1393                Bytes::from_static(
1394                    b"http://localhost:8080/index/1 https://youtube.com/watch/2 http://localhost:8080/sibling/3"
1395                ),
1396                "{uri}"
1397            );
1398        }
1399    }
1400
1401    /// STATEMENT: A scope containing only a default service still limits handling to its own prefix.
1402    ///
1403    /// HOW:
1404    /// - Mount a `Created` default service under `/app` without registering child resources.
1405    /// - Assert `/app/path` returns 201 and `/other` returns 404.
1406    #[crate::rt_test]
1407    async fn test_scope_default_service_only() {
1408        let srv = init_service(App::new().service(web::scope("/app").default_service(
1409            async |r: WebRequest<()>| Ok::<_, Infallible>(r.into_response(HttpResponse::Created())),
1410        )))
1411        .await;
1412        let resp = call_service(&srv, TestRequest::with_uri("/app/path").to_request()).await;
1413        assert_eq!(resp.status(), StatusCode::CREATED);
1414        let resp = call_service(&srv, TestRequest::with_uri("/other").to_request()).await;
1415        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
1416    }
1417}