ntex/web/app.rs
1#![allow(clippy::new_without_default)]
2use std::marker::PhantomData;
3
4use crate::error::{Failure, IntoFailure};
5use crate::http::{Request, Response};
6use crate::router::ResourceDef;
7use crate::service::{Identity, ServiceChainFactory, map_state_factory};
8use crate::{Cfg, IntoServiceFactory, Middleware, Service, ServiceFactory, factory};
9
10use super::app_service::{AppFactory, WebServiceRouter};
11use super::config::{ServiceConfig, WebAppConfig};
12use super::error::{WebError, WebResponseError};
13use super::service::{AppServiceFactory, ServiceFactoryWrapper, WebServiceFactory};
14use super::stack::{Filter, WebStack};
15use super::{HttpService, Resource, Route, State, WebRequest, WebResponse};
16
17/// The main builder for a web application.
18///
19/// Start with `App::new()` then add routes, resources,
20/// scopes, middleware, filters, application state, and a fallback response.
21///
22/// Middleware and filters run before routing. ntex then chooses the resource
23/// or scope that matches the request. If nothing matches, the application
24/// returns `404 Not Found` unless you provide a custom fallback.
25///
26/// Add application-wide settings, such as middleware, filters,
27/// [`App::with_config()`], and case-insensitive routing, before adding the
28/// first route or service. After that, the builder becomes [`AppServices`],
29/// where you can continue adding routes and services.
30///
31/// ```rust
32/// use ntex::web::{self, middleware, App, HttpResponse};
33///
34/// App::default()
35/// .middleware(middleware::Logger::default())
36/// .service(
37/// web::resource("/users")
38/// .route(web::get().to(async || "users"))
39/// .route(web::post().to(async || HttpResponse::Created())),
40/// )
41/// .default_service(
42/// web::to(async || HttpResponse::NotFound().body("Not found")),
43/// );
44/// ```
45#[derive(derive_more::Debug)]
46#[debug("App")]
47pub struct App<St: State, In = (), Out = In, M = Identity, F = Filter<St, In>> {
48 middleware: M,
49 filter: ServiceChainFactory<F, St, WebRequest<In>>,
50 external: Vec<ResourceDef>,
51 config: Option<Cfg<WebAppConfig>>,
52 case_insensitive: bool,
53 ph: PhantomData<Out>,
54}
55
56/// An application builder that already has routing configuration.
57///
58/// You usually do not need to name this type. It is returned naturally after
59/// calling [`App::route()`], [`App::service()`], [`App::configure()`], or
60/// [`App::default_service()`].
61///
62/// From here, you can add more routes and services or set the application
63/// fallback. Return the finished builder from the factory passed to
64/// [`web::server()`]. The [`AppServices::build()`] and
65/// [`AppServices::build_with()`] methods are available when you need to
66/// connect the application to a lower-level HTTP service yourself.
67///
68/// [`web::server()`]: super::server
69#[derive(derive_more::Debug)]
70#[debug("AppServices")]
71pub struct AppServices<St: State, In, Out, M, F> {
72 middleware: M,
73 filter: ServiceChainFactory<F, St, WebRequest<In>>,
74 services: Vec<Box<dyn AppServiceFactory<St, Out>>>,
75 default: Option<HttpService<St, Out>>,
76 external: Vec<ResourceDef>,
77 config: Option<Cfg<WebAppConfig>>,
78 case_insensitive: bool,
79 ph: PhantomData<In>,
80}
81
82impl Default for App<()> {
83 fn default() -> Self {
84 App {
85 middleware: Identity,
86 filter: factory(Filter::new()),
87 config: None,
88 external: Vec::new(),
89 case_insensitive: false,
90 ph: PhantomData,
91 }
92 }
93}
94
95impl<St: State, In> App<St, In, In> {
96 /// Create application builder. Application can be configured with a builder-like pattern.
97 #[must_use]
98 pub fn new() -> Self {
99 App {
100 middleware: Identity,
101 filter: factory(Filter::new()),
102 config: None,
103 external: Vec::new(),
104 case_insensitive: false,
105 ph: PhantomData,
106 }
107 }
108}
109
110impl<St, In, Out, M, F> App<St, In, Out, M, F>
111where
112 St: State,
113 In: 'static,
114 Out: 'static,
115 F: ServiceFactory<
116 St,
117 WebRequest<In>,
118 Res = WebRequest<Out>,
119 Error = WebError<St, St::Error>,
120 InitError = Failure,
121 >,
122{
123 /// Run external configuration as part of the application building
124 /// process.
125 ///
126 /// This function is useful for moving parts of configuration to a
127 /// different module or even library. For example,
128 /// some of the resource's configuration could be moved to different module.
129 ///
130 /// ```rust,ignore
131 /// use ntex::web::{self, middleware, App, HttpResponse};
132 ///
133 /// // this function could be located in different module
134 /// fn config(cfg: &mut web::ServiceConfig) {
135 /// cfg.service(web::resource("/test")
136 /// .route(web::get().to(async || { HttpResponse::Ok() }))
137 /// .route(web::head().to(async || { HttpResponse::MethodNotAllowed() }))
138 /// );
139 /// }
140 ///
141 /// fn main() {
142 /// let app = App::default()
143 /// .middleware(middleware::Logger::default())
144 /// .configure(config) // <- register resources
145 /// .route("/index.html", web::get().to(async || { HttpResponse::Ok() }));
146 /// }
147 /// ```
148 #[must_use]
149 pub fn configure(
150 self,
151 f: impl FnOnce(&mut ServiceConfig<St, Out>),
152 ) -> AppServices<St, In, Out, M, F> {
153 let mut cfg = ServiceConfig::new(self.external);
154 f(&mut cfg);
155
156 AppServices {
157 services: cfg.services,
158 default: None,
159 filter: self.filter,
160 middleware: self.middleware,
161 config: self.config,
162 external: cfg.external,
163 case_insensitive: self.case_insensitive,
164 ph: PhantomData,
165 }
166 }
167
168 /// Register a route for an application path.
169 ///
170 /// This is shorthand for creating a [`Resource`] with one route and
171 /// registering it with [`App::service()`]. The route's method and custom
172 /// guards are promoted to resource guards.
173 /// A request must match one of the route's methods and every custom guard.
174 ///
175 /// Each call creates a separate resource, so the same path can be
176 /// registered more than once with different guards.
177 ///
178 /// ```rust
179 /// use ntex::web::{self, App, HttpResponse};
180 ///
181 /// App::default()
182 /// .route("/items", web::get().to(async || "list"))
183 /// .route("/items", web::post().to(async || HttpResponse::Created()));
184 /// ```
185 #[must_use]
186 pub fn route(self, path: &str, mut route: Route<St, Out>) -> AppServices<St, In, Out, M, F> {
187 self.service(
188 Resource::new(path)
189 .add_guards(route.take_guards())
190 .route(route),
191 )
192 }
193
194 /// Registers a web service with the application.
195 ///
196 /// A service defines its own path and guards through [`WebServiceFactory`].
197 /// Common services include [`Resource`], [`Scope`](crate::web::Scope), handlers created with
198 /// route attribute macros, and custom services built with `web::service()`.
199 ///
200 /// Use a resource to group several routes, filters, middleware, or a
201 /// fallback under one path. Use a scope to group services under a shared
202 /// path prefix.
203 ///
204 /// If no registered service matches the request path and guards, the
205 /// application's default service is used.
206 ///
207 /// Registered services and the default service are created lazily, on the
208 /// first request that reaches them, not when the application starts. If a
209 /// factory fails, application startup still succeeds; that request gets
210 /// `500 Internal Server Error` and creation is retried on the next one.
211 ///
212 /// ```rust
213 /// use ntex::web::{self, App, HttpResponse};
214 ///
215 /// App::default()
216 /// .service(
217 /// web::resource("/users")
218 /// .route(web::get().to(async || "users"))
219 /// .route(web::post().to(async || HttpResponse::Created())),
220 /// )
221 /// .service(
222 /// web::scope("/api")
223 /// .route("/health", web::get().to(async || "OK")),
224 /// );
225 /// ```
226 #[must_use]
227 pub fn service<S>(self, factory: S) -> AppServices<St, In, Out, M, F>
228 where
229 S: WebServiceFactory<St, Out> + 'static,
230 {
231 AppServices {
232 services: vec![Box::new(ServiceFactoryWrapper::new(factory))],
233 default: None,
234 filter: self.filter,
235 middleware: self.middleware,
236 config: self.config,
237 external: self.external,
238 case_insensitive: self.case_insensitive,
239 ph: PhantomData,
240 }
241 }
242
243 /// Set the fallback service for unmatched application requests.
244 ///
245 /// The fallback is called when no top-level resource or scope matches the
246 /// request path and guards. Without a custom fallback, the application
247 /// returns `404 Not Found`.
248 ///
249 /// A matched resource or scope handles its own routing failures, so its
250 /// requests do not fall through to this service.
251 ///
252 /// ```rust
253 /// use ntex::web::{self, App, HttpRequest, HttpResponse};
254 ///
255 /// async fn not_found(req: HttpRequest) -> HttpResponse {
256 /// HttpResponse::NotFound()
257 /// .body(format!("No resource for {}", req.path()))
258 /// }
259 ///
260 /// App::default()
261 /// .route("/health", web::get().to(async || "ready"))
262 /// .default_service(web::to(not_found));
263 /// ```
264 #[must_use]
265 pub fn default_service<U>(
266 self,
267 f: impl IntoServiceFactory<U, St, WebRequest<Out>>,
268 ) -> AppServices<St, In, Out, M, F>
269 where
270 U: ServiceFactory<St, WebRequest<Out>, Res = WebResponse> + 'static,
271 U::Error: WebResponseError<St, St::Error>,
272 U::InitError: IntoFailure,
273 {
274 // create and configure default resource
275 let default = Some(HttpService::new(
276 f.into_factory()
277 .map_err(WebError::from_err)
278 .map_init_err(IntoFailure::fail),
279 ));
280
281 AppServices {
282 default,
283 services: Vec::new(),
284 filter: self.filter,
285 middleware: self.middleware,
286 config: self.config,
287 external: self.external,
288 case_insensitive: self.case_insensitive,
289 ph: PhantomData,
290 }
291 }
292
293 /// Register an external resource.
294 ///
295 /// External resources are useful for URL generation purposes only
296 /// and are never considered for matching at request time. Calls to
297 /// `HttpRequest::url_for()` will work as expected. The name must not be
298 /// used by another resource of the application.
299 ///
300 /// ```rust
301 /// use ntex::web::{self, App, HttpRequest, HttpResponse, error::UrlGenerationError};
302 ///
303 /// async fn index(req: HttpRequest) -> Result<HttpResponse, UrlGenerationError> {
304 /// let url = req.url_for("youtube", &["asdlkjqme"])?;
305 /// assert_eq!(url.as_str(), "https://youtube.com/watch/asdlkjqme");
306 /// Ok(HttpResponse::Ok().into())
307 /// }
308 ///
309 /// fn main() {
310 /// let app = App::default()
311 /// .external_resource("youtube", "https://youtube.com/watch/{video_id}")
312 /// .service(web::resource("/index.html").route(
313 /// web::get().to(index)));
314 /// }
315 /// ```
316 #[must_use]
317 pub fn external_resource(mut self, name: impl AsRef<str>, url: impl AsRef<str>) -> Self {
318 let mut rdef = ResourceDef::new(url.as_ref());
319 rdef.set_name(name.as_ref());
320 self.external.push(rdef);
321 self
322 }
323
324 /// Set the application's runtime configuration.
325 ///
326 /// [`WebAppConfig`] contains connection metadata used by the application,
327 /// such as the host, secure-connection flag, local address, and request pool
328 /// size. It can also store typed configuration values with
329 /// [`WebAppConfig::set_value()`]; those values are available through
330 /// [`HttpRequest::app_value()`](crate::web::HttpRequest::app_value) and [`WebRequest::app_value()`].
331 ///
332 /// Without an explicit configuration, each request uses the
333 /// [`WebAppConfig`] from its I/O context, or the default configuration if
334 /// the request has no associated I/O object. This method overrides that
335 /// selection for every request handled by this application.
336 ///
337 /// This configuration is separate from the service-level application state
338 /// represented by `St`. To register routes and services from an external
339 /// function, use [`App::configure()`] instead.
340 ///
341 /// ```rust
342 /// use ntex::web::{self, App, HttpRequest, WebAppConfig};
343 ///
344 /// async fn index(req: HttpRequest) -> String {
345 /// let value = req.app_value::<usize>().copied().unwrap_or_default();
346 /// format!("Configured value: {value}")
347 /// }
348 ///
349 /// let config = WebAppConfig::new()
350 /// .set_host("www.example.com".to_owned())
351 /// .set_secure()
352 /// .set_value(42usize);
353 ///
354 /// App::default()
355 /// .with_config(config)
356 /// .route("/", web::get().to(index));
357 /// ```
358 #[must_use]
359 pub fn with_config(mut self, cfg: impl Into<Cfg<WebAppConfig>>) -> Self {
360 self.config = Some(cfg.into());
361 self
362 }
363
364 /// Registers a request filter.
365 ///
366 /// Application filters run before the application router selects a
367 /// resource or scope. Filters are called in registration order, and each
368 /// filter receives the [`WebRequest`] returned by the previous one.
369 ///
370 /// A filter can inspect or modify the request, or use
371 /// [`WebRequest::map_state()`] to change its request-local state type. It
372 /// must return another `WebRequest` to continue processing. Returning an
373 /// error stops the filter chain and prevents routing; the error is handled
374 /// through [`WebResponseError`].
375 ///
376 /// Application middleware wraps the filter and router, so middleware runs
377 /// before filters on the inbound path.
378 ///
379 /// ```rust
380 /// use std::convert::Infallible;
381 /// use ntex::web::{self, App, WebRequest};
382 ///
383 /// async fn authenticate(
384 /// req: WebRequest<()>,
385 /// ) -> Result<WebRequest<&'static str>, Infallible> {
386 /// Ok(req.map_state(|()| "alice"))
387 /// }
388 ///
389 /// async fn index(_state: &(), user: &'static str) -> String {
390 /// format!("Hello, {user}!")
391 /// }
392 ///
393 /// App::new()
394 /// .filter(authenticate)
395 /// .route("/", web::get().to_with_state(index));
396 /// ```
397 #[must_use]
398 pub fn filter<Sf, R>(
399 self,
400 filter: impl IntoServiceFactory<Sf, St, WebRequest<Out>>,
401 ) -> App<
402 St,
403 In,
404 R,
405 M,
406 impl ServiceFactory<
407 St,
408 WebRequest<In>,
409 Res = WebRequest<R>,
410 Error = WebError<St, St::Error>,
411 InitError = Failure,
412 >,
413 >
414 where
415 Sf: ServiceFactory<St, WebRequest<Out>, Res = WebRequest<R>>,
416 Sf::Error: WebResponseError<St, St::Error>,
417 Sf::InitError: IntoFailure,
418 {
419 App {
420 filter: self.filter.and_then(
421 filter
422 .into_factory()
423 .map_err(WebError::from_err)
424 .map_init_err(IntoFailure::fail),
425 ),
426 middleware: self.middleware,
427 config: self.config,
428 external: self.external,
429 case_insensitive: self.case_insensitive,
430 ph: PhantomData,
431 }
432 }
433
434 /// Registers a middleware for this application.
435 ///
436 /// Use application middleware for work that should apply to every request,
437 /// such as logging, response headers, or authentication. It runs before
438 /// the application filter and router on the way in, and can inspect or
439 /// modify the response on the way back.
440 ///
441 /// Middleware may also return a response without calling the service it
442 /// wraps. In that case, the rest of the application pipeline is skipped.
443 ///
444 /// Requests pass through middleware in the order it was added. Responses
445 /// travel back in the opposite order. In this example, `DefaultHeaders`
446 /// sees the request before `Logger`, while `Logger` sees the response
447 /// before `DefaultHeaders`.
448 ///
449 /// Custom middleware should call the wrapped service through
450 /// [`Ctx::call()`](crate::Ctx::call) so readiness and lifecycle events are handled
451 /// correctly.
452 ///
453 /// ```rust
454 /// use ntex::web::{self, middleware, App};
455 ///
456 /// App::default()
457 /// .middleware(
458 /// middleware::DefaultHeaders::new()
459 /// .header("x-application", "example"),
460 /// )
461 /// .middleware(middleware::Logger::default())
462 /// .route("/", web::get().to(async || "Hello"));
463 /// ```
464 #[must_use]
465 #[doc(alias = "wrap")]
466 pub fn middleware<U>(self, mw: U) -> App<St, In, Out, WebStack<St, U, M>, F> {
467 App {
468 middleware: WebStack::new(mw, self.middleware),
469 filter: self.filter,
470 config: self.config,
471 external: self.external,
472 case_insensitive: self.case_insensitive,
473 ph: PhantomData,
474 }
475 }
476
477 #[must_use]
478 /// Use ascii case-insensitive routing.
479 ///
480 /// Only static segments could be case-insensitive.
481 pub fn case_insensitive_routing(mut self) -> Self {
482 self.case_insensitive = true;
483 self
484 }
485}
486
487impl<St, In, Out, M, F> AppServices<St, In, Out, M, F>
488where
489 St: State,
490 Out: 'static,
491 F: ServiceFactory<
492 St,
493 WebRequest<In>,
494 Res = WebRequest<Out>,
495 Error = WebError<St, St::Error>,
496 InitError = Failure,
497 >,
498{
499 /// Register a route for an application path.
500 ///
501 /// This is shorthand for creating a [`Resource`] with one route and
502 /// registering it with [`AppServices::service()`]. The route's method and
503 /// custom guards are promoted to resource guards.
504 /// A request must match one of the route's methods and every custom guard.
505 ///
506 /// Consequently, if those guards reject a request, the generated resource
507 /// does not match and the application router continues searching. If
508 /// nothing else matches, the application default service is used. To use a
509 /// resource-level fallback such as the built-in `405 Method Not Allowed`,
510 /// register an explicit [`Resource`] and add routes with
511 /// [`Resource::route()`].
512 ///
513 /// Each call creates a separate resource, so the same path can be
514 /// registered more than once with different guards.
515 ///
516 /// ```rust
517 /// use ntex::web::{self, App, HttpResponse};
518 ///
519 /// App::default()
520 /// .route("/items", web::get().to(async || "list"))
521 /// .route(
522 /// "/items",
523 /// web::post().to(async || HttpResponse::Created()),
524 /// );
525 /// ```
526 #[must_use]
527 pub fn route(self, path: &str, mut route: Route<St, Out>) -> Self {
528 self.service(
529 Resource::new(path)
530 .add_guards(route.take_guards())
531 .route(route),
532 )
533 }
534
535 /// Registers another web service with the application.
536 ///
537 /// This has the same behavior as [`App::service()`]. The service supplies
538 /// its own path and guards and becomes part of the application's top-level
539 /// router.
540 ///
541 /// If none of the registered services match, the application's default
542 /// service is used.
543 #[must_use]
544 pub fn service<S>(mut self, factory: S) -> Self
545 where
546 S: WebServiceFactory<St, Out> + 'static,
547 {
548 self.services
549 .push(Box::new(ServiceFactoryWrapper::new(factory)));
550 self
551 }
552
553 /// Set the fallback service for unmatched application requests.
554 ///
555 /// The fallback is called when no top-level resource or scope matches the
556 /// request path and guards. Without a custom fallback, the application
557 /// returns `404 Not Found`.
558 ///
559 /// A matched resource or scope handles its own routing failures, so its
560 /// requests do not fall through to this service.
561 ///
562 /// ```rust
563 /// use ntex::web::{self, App, HttpRequest, HttpResponse};
564 ///
565 /// async fn not_found(req: HttpRequest) -> HttpResponse {
566 /// HttpResponse::NotFound()
567 /// .body(format!("No resource for {}", req.path()))
568 /// }
569 ///
570 /// App::default()
571 /// .route("/health", web::get().to(async || "ready"))
572 /// .default_service(web::to(not_found));
573 /// ```
574 #[must_use]
575 pub fn default_service<U>(mut self, f: impl IntoServiceFactory<U, St, WebRequest<Out>>) -> Self
576 where
577 U: ServiceFactory<St, WebRequest<Out>, Res = WebResponse> + 'static,
578 U::Error: WebResponseError<St, St::Error>,
579 U::InitError: IntoFailure,
580 {
581 // create and configure default resource
582 self.default = Some(HttpService::new(
583 f.into_factory()
584 .map_err(WebError::from_err)
585 .map_init_err(IntoFailure::fail),
586 ));
587
588 self
589 }
590}
591
592impl<St, In, Out, M, F> AppServices<St, In, Out, M, F>
593where
594 St: State,
595 In: 'static,
596 Out: 'static,
597 F: ServiceFactory<
598 St,
599 WebRequest<In>,
600 Res = WebRequest<Out>,
601 Error = WebError<St, St::Error>,
602 InitError = Failure,
603 > + 'static,
604 M: Middleware<WebServiceRouter<St, In, Out, F::Service>, St> + 'static,
605 M::Service: Service<St, WebRequest<()>, Res = WebResponse, Error = WebError<St, St::Error>>,
606{
607 /// Builds the application into a service factory.
608 ///
609 /// The returned factory accepts [`Request`] values and uses application
610 /// state supplied by the surrounding service pipeline. It can be passed to
611 /// [`HttpService`] when building an HTTP server manually.
612 ///
613 /// Applications passed to [`web::server()`] do not normally need an
614 /// explicit call to `build()`.
615 ///
616 /// ```rust
617 /// use ntex::web;
618 ///
619 /// let factory = web::App::default()
620 /// .route("/", web::get().to(async || "Hello"))
621 /// .build();
622 /// ```
623 ///
624 /// [`HttpService`]: crate::http::HttpService
625 /// [`web::server()`]: super::server
626 pub fn build(
627 self,
628 ) -> impl ServiceFactory<
629 St,
630 Request,
631 Res = Response,
632 Error = WebError<St, St::Error>,
633 InitError = Failure,
634 > {
635 IntoServiceFactory::<AppFactory<St, In, Out, M, F>, St, Request>::into_factory(self)
636 }
637}
638
639impl<St, In, Out, M, F> AppServices<St, In, Out, M, F>
640where
641 St: State,
642 In: 'static,
643 Out: 'static,
644 F: ServiceFactory<
645 St,
646 WebRequest<In>,
647 Res = WebRequest<Out>,
648 Error = WebError<St, St::Error>,
649 InitError = Failure,
650 > + 'static,
651 M: Middleware<WebServiceRouter<St, In, Out, F::Service>, St> + 'static,
652 M::Service: Service<St, WebRequest<()>, Res = WebResponse, Error = WebError<St, St::Error>>,
653{
654 /// Builds the application with a fixed application state.
655 ///
656 /// Unlike [`AppServices::build()`], which takes its application state from
657 /// the surrounding service pipeline, this method stores `state` in the
658 /// returned factory. Web handlers, filters, middleware, and services use
659 /// this fixed state even when the outer pipeline uses a different state
660 /// type.
661 ///
662 /// ```rust
663 /// use ntex::web;
664 ///
665 /// #[derive(Clone)]
666 /// struct AppState {
667 /// greeting: &'static str,
668 /// }
669 ///
670 /// impl web::State for AppState {
671 /// type Error = web::DefaultError;
672 /// }
673 ///
674 /// async fn index(state: &AppState, _request_state: ()) -> String {
675 /// state.greeting.to_owned()
676 /// }
677 ///
678 /// let app = web::App::<AppState>::new()
679 /// .route("/", web::get().to_with_state(index))
680 /// .build_with::<()>(AppState { greeting: "Hello" });
681 /// ```
682 pub fn build_with<Outer>(
683 self,
684 state: St,
685 ) -> impl ServiceFactory<
686 Outer,
687 Request,
688 Res = Response,
689 Error = WebError<St, St::Error>,
690 InitError = Failure,
691 >
692 where
693 St: Clone,
694 {
695 map_state_factory(
696 state,
697 IntoServiceFactory::<AppFactory<St, In, Out, M, F>, St, Request>::into_factory(self),
698 )
699 }
700}
701
702impl<St, In, Out, M, F> IntoServiceFactory<AppFactory<St, In, Out, M, F>, St, Request>
703 for AppServices<St, In, Out, M, F>
704where
705 St: State,
706 In: 'static,
707 Out: 'static,
708 F: ServiceFactory<
709 St,
710 WebRequest<In>,
711 Res = WebRequest<Out>,
712 Error = WebError<St, St::Error>,
713 InitError = Failure,
714 > + 'static,
715 M: Middleware<WebServiceRouter<St, In, Out, F::Service>, St> + 'static,
716 M::Service: Service<St, WebRequest<()>, Res = WebResponse, Error = WebError<St, St::Error>>,
717{
718 fn into_factory(self) -> AppFactory<St, In, Out, M, F> {
719 AppFactory::new(
720 self.middleware,
721 self.filter,
722 self.services,
723 self.default,
724 self.config,
725 self.external,
726 self.case_insensitive,
727 )
728 }
729}
730
731#[cfg(test)]
732mod tests {
733 use std::{cell::Cell, convert::Infallible, rc::Rc};
734
735 use super::*;
736 use crate::http::{Method, StatusCode, header, header::HeaderValue};
737 use crate::web::test::{TestRequest, call_service, init_service, read_body};
738 use crate::web::{self, HttpRequest, HttpResponse, middleware::DefaultHeaders};
739
740 /// STATEMENT: Applications route the supplied target without automatically normalizing it.
741 ///
742 /// HOW:
743 /// - Route canonical and literal non-canonical paths through `App::new` and `App::default`.
744 /// - Check that dot segments are not collapsed and handlers retain raw path/query spelling.
745 /// - Check that the router's existing segment decoding still matches escaped characters.
746 #[crate::rt_test]
747 async fn test_request_target_preserved() {
748 for app in [App::new(), App::default()] {
749 let srv = init_service(
750 app.route(
751 "/test",
752 web::get().to(async |req: HttpRequest| {
753 assert!(matches!(req.path(), "/test" | "/%74est"));
754 "canonical"
755 }),
756 )
757 .route(
758 "/a/../test",
759 web::get().to(async |req: HttpRequest| {
760 assert_eq!(req.path(), "/a/../%74est");
761 assert_eq!(req.query_string(), "x=%7e");
762 "raw"
763 }),
764 ),
765 )
766 .await;
767 for (path, body) in [
768 ("/test", "canonical"),
769 ("/%74est", "canonical"),
770 ("/a/../%74est?x=%7e", "raw"),
771 ] {
772 let res = call_service(&srv, TestRequest::with_uri(path).to_request()).await;
773 assert_eq!(res.status(), StatusCode::OK);
774 assert_eq!(read_body(res).await, body);
775 }
776 let res = call_service(&srv, TestRequest::with_uri("/x/../%74est").to_request()).await;
777 assert_eq!(res.status(), StatusCode::NOT_FOUND);
778 }
779 }
780
781 /// STATEMENT: Resource fallbacks and application fallbacks handle different routing misses.
782 ///
783 /// HOW:
784 /// - Check a registered path succeeds and an unknown path defaults to 404.
785 /// - Configure application and resource defaults, then assert 405 for an unknown path,
786 /// OK for a matching GET, and 201 for a method miss on the configured resource.
787 #[crate::rt_test]
788 async fn test_default_resource() {
789 let srv = App::new()
790 .service(web::resource("/test").to(async || HttpResponse::Ok()))
791 .build()
792 .pipeline(())
793 .await
794 .unwrap();
795 let req = TestRequest::with_uri("/test").to_request();
796 let resp = srv.call(req).await.unwrap();
797 assert_eq!(resp.status(), StatusCode::OK);
798
799 let req = TestRequest::with_uri("/blah").to_request();
800 let resp = srv.call(req).await.unwrap();
801 assert_eq!(resp.status(), StatusCode::NOT_FOUND);
802
803 let srv = App::new()
804 .service(web::resource("/test").to(async || HttpResponse::Ok()))
805 .service(
806 web::resource("/test2")
807 .default_service(async move |r: WebRequest<()>| {
808 Ok::<_, Infallible>(r.into_response(HttpResponse::Created()))
809 })
810 .route(web::get().to(async || HttpResponse::Ok())),
811 )
812 .default_service(async move |r: WebRequest<()>| {
813 Ok::<_, Infallible>(r.into_response(HttpResponse::MethodNotAllowed()))
814 })
815 .build()
816 .pipeline(())
817 .await
818 .unwrap();
819
820 let req = TestRequest::with_uri("/blah").to_request();
821 let resp = srv.call(req).await.unwrap();
822 assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
823
824 let req = TestRequest::with_uri("/test2").to_request();
825 let resp = srv.call(req).await.unwrap();
826 assert_eq!(resp.status(), StatusCode::OK);
827
828 let req = TestRequest::with_uri("/test2")
829 .method(Method::POST)
830 .to_request();
831 let resp = srv.call(req).await.unwrap();
832 assert_eq!(resp.status(), StatusCode::CREATED);
833 }
834
835 /// STATEMENT: Application filters execute before successful route handling.
836 ///
837 /// HOW:
838 /// - Install a filter that sets a shared flag and forwards the request.
839 /// - Call `/test` and assert an OK response and the flag being set.
840 #[crate::rt_test]
841 async fn test_filter() {
842 let filter = Rc::new(Cell::new(false));
843 let filter2 = filter.clone();
844 let srv = init_service(
845 App::new()
846 .filter(async move |req: WebRequest<()>| {
847 filter2.set(true);
848 Ok::<_, Infallible>(req)
849 })
850 .route("/test", web::get().to(async || HttpResponse::Ok())),
851 )
852 .await;
853 let req = TestRequest::with_uri("/test").to_request();
854 let resp = call_service(&srv, req).await;
855 assert_eq!(resp.status(), StatusCode::OK);
856 assert!(filter.get());
857 }
858
859 /// STATEMENT: Application middleware adds configured default response headers.
860 ///
861 /// HOW:
862 /// - Wrap an application route with `DefaultHeaders` specifying content type `0001`.
863 /// - Request the route and assert OK and the configured header value.
864 #[crate::rt_test]
865 async fn test_wrap() {
866 let srv = init_service(
867 App::new()
868 .middleware(
869 DefaultHeaders::new()
870 .header(header::CONTENT_TYPE, HeaderValue::from_static("0001")),
871 )
872 .route("/test", web::get().to(async || HttpResponse::Ok())),
873 )
874 .await;
875 let req = TestRequest::with_uri("/test").to_request();
876 let resp = call_service(&srv, req).await;
877 assert_eq!(resp.status(), StatusCode::OK);
878 assert_eq!(
879 resp.headers().get(header::CONTENT_TYPE).unwrap(),
880 HeaderValue::from_static("0001")
881 );
882 }
883
884 /// STATEMENT: An async closure installed with `fn_layer` works as application middleware.
885 ///
886 /// HOW:
887 /// - Install `fn_layer` with the annotations shown in the web guide; it adds a header
888 /// to the inner response.
889 /// - Call the route and assert OK and the header set by the closure.
890 #[crate::rt_test]
891 async fn test_fn_layer_wrap() {
892 let srv = init_service(
893 App::new()
894 .middleware(crate::service::fn_layer(
895 async |req: WebRequest<()>, ctx| {
896 let mut res: WebResponse = ctx.call(req).await?;
897 res.headers_mut()
898 .insert(header::CONTENT_TYPE, HeaderValue::from_static("0002"));
899 Ok::<_, WebError>(res)
900 },
901 ))
902 .route("/test", web::get().to(async || HttpResponse::Ok())),
903 )
904 .await;
905 let resp = call_service(&srv, TestRequest::with_uri("/test").to_request()).await;
906 assert_eq!(resp.status(), StatusCode::OK);
907 assert_eq!(
908 resp.headers().get(header::CONTENT_TYPE).unwrap(),
909 HeaderValue::from_static("0002")
910 );
911 }
912
913 /// STATEMENT: Case-insensitive routing accepts paths differing only in letter case.
914 ///
915 /// HOW:
916 /// - Enable `case_insensitive_routing` and register `/test`.
917 /// - Request `/test` and `/Test` and assert both responses are OK.
918 #[crate::rt_test]
919 async fn test_case_insensitive_router() {
920 let srv = init_service(
921 App::new()
922 .case_insensitive_routing()
923 .route("/test", web::get().to(async || HttpResponse::Ok())),
924 )
925 .await;
926 let req = TestRequest::with_uri("/test").to_request();
927 let resp = call_service(&srv, req).await;
928 assert_eq!(resp.status(), StatusCode::OK);
929
930 let req = TestRequest::with_uri("/Test").to_request();
931 let resp = call_service(&srv, req).await;
932 assert_eq!(resp.status(), StatusCode::OK);
933 }
934
935 /// STATEMENT: Application configuration state is available to filters and handlers.
936 ///
937 /// HOW:
938 /// - Store `10usize` through `WebAppConfig` and read it in a filter and HTTP handler.
939 /// - Assert both reads return 10 and the request completes with OK.
940 #[crate::rt_test]
941 async fn test_extension() {
942 let cfg = WebAppConfig::new().set_value(10usize);
943
944 let srv = init_service(
945 App::new()
946 .with_config(cfg)
947 .filter(async move |req: WebRequest<()>| {
948 assert_eq!(*req.app_value::<usize>().unwrap(), 10);
949 Ok::<_, Infallible>(req)
950 })
951 .service(web::resource("/").to(async move |req: HttpRequest| {
952 assert_eq!(*req.app_value::<usize>().unwrap(), 10);
953 HttpResponse::Ok()
954 })),
955 )
956 .await;
957
958 let req = TestRequest::default().to_request();
959 let resp = srv.call(req).await.unwrap();
960 assert_eq!(resp.status(), StatusCode::OK);
961 }
962
963 /// STATEMENT: Application external resources generate URLs inside request handlers.
964 ///
965 /// HOW:
966 /// - Register a `youtube` external resource and return `url_for` from `/test`.
967 /// - Assert OK and the complete URL containing the supplied video ID.
968 #[crate::rt_test]
969 async fn test_external_resource() {
970 use crate::util::Bytes;
971
972 let srv = init_service(
973 App::new()
974 .external_resource("youtube", "https://youtube.com/watch/{video_id}")
975 .route(
976 "/test",
977 web::get().to(async move |req: HttpRequest| {
978 HttpResponse::Ok()
979 .body(format!("{}", req.url_for("youtube", ["12345"]).unwrap()))
980 }),
981 ),
982 )
983 .await;
984 let req = TestRequest::with_uri("/test").to_request();
985 let resp = call_service(&srv, req).await;
986 assert_eq!(resp.status(), StatusCode::OK);
987 let body = read_body(resp).await;
988 assert_eq!(body, Bytes::from_static(b"https://youtube.com/watch/12345"));
989 }
990
991 /// STATEMENT: Reused requests retain the resource map of the application currently serving them.
992 ///
993 /// HOW:
994 /// - Initialize two applications with the same resource name but different external origins.
995 /// - Alternate repeated calls and assert every generated URL uses that application's origin.
996 #[crate::rt_test]
997 async fn test_pooled_request_resource_map() {
998 use crate::util::Bytes;
999
1000 async fn url(req: HttpRequest) -> HttpResponse {
1001 HttpResponse::Ok().body(format!("{}", req.url_for("docs", ["1"]).unwrap()))
1002 }
1003
1004 let srv1 = init_service(
1005 App::new()
1006 .external_resource("docs", "https://one.example.com/{page}")
1007 .route("/test", web::get().to(url)),
1008 )
1009 .await;
1010 let srv2 = init_service(
1011 App::new()
1012 .external_resource("docs", "https://two.example.com/{page}")
1013 .route("/test", web::get().to(url)),
1014 )
1015 .await;
1016
1017 for _ in 0..2 {
1018 for (srv, expected) in [
1019 (&srv1, &b"https://one.example.com/1"[..]),
1020 (&srv2, &b"https://two.example.com/1"[..]),
1021 ] {
1022 let req = TestRequest::with_uri("/test").to_request();
1023 let resp = call_service(srv, req).await;
1024 assert_eq!(read_body(resp).await, Bytes::from_static(expected));
1025 }
1026 }
1027 }
1028
1029 /// STATEMENT: `App::default` dispatches unmatched requests to its custom default service.
1030 ///
1031 /// HOW:
1032 /// - Configure a default service returning `Created` and request `/any`.
1033 /// - Assert status 201 and shut down the service.
1034 #[crate::rt_test]
1035 async fn test_app_default_service() {
1036 let srv =
1037 init_service(App::default().default_service(web::to(async || HttpResponse::Created())))
1038 .await;
1039 let resp = call_service(&srv, TestRequest::with_uri("/any").to_request()).await;
1040 assert_eq!(resp.status(), StatusCode::CREATED);
1041 srv.shutdown().await;
1042 }
1043
1044 /// STATEMENT: Failed lazy service initialization is retried and successful instances are cached.
1045 ///
1046 /// HOW:
1047 /// - Register route and default factories that alternate initialization failure and success.
1048 /// - Call each path three times and assert statuses 500, OK, and OK.
1049 /// - Assert only four total factory attempts occurred.
1050 #[crate::rt_test]
1051 async fn test_app_service_init_errors() {
1052 use crate::service::{fn_factory, fn_service};
1053
1054 let attempts = Rc::new(Cell::new(0));
1055 let attempts2 = attempts.clone();
1056 let failing = move || {
1057 let attempts = attempts2.clone();
1058 fn_factory(async move |(): &()| {
1059 attempts.set(attempts.get() + 1);
1060 if attempts.get() % 2 == 1 {
1061 Err(std::io::Error::other("init error"))
1062 } else {
1063 Ok(fn_service(async |req: WebRequest<()>| {
1064 Ok::<_, Infallible>(req.into_response(HttpResponse::Ok()))
1065 }))
1066 }
1067 })
1068 };
1069
1070 let srv = init_service(
1071 App::new()
1072 .service(web::service("/test").build(failing()))
1073 .default_service(failing()),
1074 )
1075 .await;
1076
1077 // failed services are not cached, next request creates them again
1078 for path in ["/test", "/unknown"] {
1079 let resp = call_service(&srv, TestRequest::with_uri(path).to_request()).await;
1080 assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
1081 let resp = call_service(&srv, TestRequest::with_uri(path).to_request()).await;
1082 assert_eq!(resp.status(), StatusCode::OK);
1083 let resp = call_service(&srv, TestRequest::with_uri(path).to_request()).await;
1084 assert_eq!(resp.status(), StatusCode::OK);
1085 }
1086 assert_eq!(attempts.get(), 4);
1087 }
1088
1089 /// STATEMENT: Lazily created routes bind before dispatch and participate in aggregate readiness.
1090 ///
1091 /// HOW:
1092 /// - Register raw gated services as a route and fallback, then verify lazy binding and waiting.
1093 /// - Invalidate the cached route and verify app readiness and calls to either route wait.
1094 /// - Restore the route, verify the filter and fallback retain their caches, then shut down.
1095 #[crate::rt_test]
1096 async fn lazy_routes_bind_current_scope_before_dispatch() {
1097 use std::{future::Future, task::Context, task::Waker};
1098
1099 use crate::service::{BindCtx, Ctx, ReadyNotifier, fn_factory};
1100
1101 #[derive(Default)]
1102 struct Gate {
1103 changed: ReadyNotifier,
1104 available: Cell<bool>,
1105 binds: Cell<usize>,
1106 checks: Cell<usize>,
1107 calls: Cell<usize>,
1108 shutdowns: Cell<usize>,
1109 }
1110
1111 struct Gated(Rc<Gate>);
1112
1113 impl Service<(), WebRequest<()>> for Gated {
1114 type Res = WebResponse;
1115 type Error = Infallible;
1116
1117 fn bind(&self, ctx: BindCtx<'_>) {
1118 self.0.binds.set(self.0.binds.get() + 1);
1119 ctx.subscribe(&self.0.changed);
1120 }
1121
1122 async fn ready(&self, _: Ctx<'_, Self>) -> Result<(), Infallible> {
1123 self.0.checks.set(self.0.checks.get() + 1);
1124 if !self.0.available.get() {
1125 std::future::pending::<()>().await;
1126 }
1127 Ok(())
1128 }
1129
1130 async fn call(
1131 &self,
1132 req: WebRequest<()>,
1133 _: Ctx<'_, Self>,
1134 ) -> Result<WebResponse, Infallible> {
1135 self.0.calls.set(self.0.calls.get() + 1);
1136 Ok(req.into_response(HttpResponse::Ok()))
1137 }
1138
1139 async fn shutdown(&self, _: Ctx<'_, Self>) {
1140 self.0.shutdowns.set(self.0.shutdowns.get() + 1);
1141 }
1142 }
1143
1144 let route = Rc::new(Gate::default());
1145 let default = Rc::new(Gate::default());
1146 let filter_checks = Rc::new(Cell::new(0));
1147 let checks = filter_checks.clone();
1148 let factory = |gate: Rc<Gate>| {
1149 fn_factory(async move |(): &()| Ok::<_, Infallible>(Gated(gate.clone())))
1150 };
1151 let srv = init_service(
1152 App::new()
1153 .filter(
1154 crate::factory(async |req: WebRequest<()>| Ok::<_, Infallible>(req)).readiness(
1155 async move |(): &()| {
1156 checks.set(checks.get() + 1);
1157 Ok(())
1158 },
1159 ),
1160 )
1161 .service(web::service("/test").build(factory(route.clone())))
1162 .default_service(factory(default.clone())),
1163 )
1164 .await;
1165 srv.ready().await.unwrap();
1166 assert_eq!((route.binds.get(), default.binds.get()), (0, 0));
1167
1168 for (path, gate) in [("/test", &route), ("/missing", &default)] {
1169 let mut call = Box::pin(srv.call(TestRequest::with_uri(path).to_request()));
1170 let mut cx = Context::from_waker(Waker::noop());
1171 assert!(call.as_mut().poll(&mut cx).is_pending());
1172 assert_eq!(gate.binds.get(), 1);
1173 assert_eq!(gate.calls.get(), 0);
1174 gate.available.set(true);
1175 gate.changed.notify();
1176 assert_eq!(call.await.unwrap().status(), StatusCode::OK);
1177 assert_eq!(gate.checks.get(), 2);
1178 }
1179
1180 srv.ready().await.unwrap();
1181 let before = filter_checks.get();
1182 route.available.set(false);
1183 route.changed.notify();
1184 let mut ready = Box::pin(srv.ready());
1185 let mut cx = Context::from_waker(Waker::noop());
1186 assert!(ready.as_mut().poll(&mut cx).is_pending());
1187 assert_eq!(filter_checks.get(), before);
1188 let mut call = Box::pin(srv.call(TestRequest::with_uri("/test").to_request()));
1189 assert!(call.as_mut().poll(&mut cx).is_pending());
1190 let mut fallback = Box::pin(srv.call(TestRequest::with_uri("/missing").to_request()));
1191 assert!(fallback.as_mut().poll(&mut cx).is_pending());
1192 assert_eq!(default.checks.get(), 2);
1193 assert_eq!(route.calls.get(), 1);
1194 route.available.set(true);
1195 route.changed.notify();
1196 ready.await.unwrap();
1197 assert_eq!(call.await.unwrap().status(), StatusCode::OK);
1198 assert_eq!(fallback.await.unwrap().status(), StatusCode::OK);
1199 assert_eq!(filter_checks.get(), before);
1200 assert_eq!(default.checks.get(), 2);
1201 assert_eq!((route.binds.get(), default.binds.get()), (1, 1));
1202 srv.shutdown().await;
1203 assert_eq!((route.shutdowns.get(), default.shutdowns.get()), (1, 1));
1204 }
1205
1206 /// STATEMENT: Application filter errors become responses instead of reaching the route handler.
1207 ///
1208 /// HOW:
1209 /// - Reject `/denied` in a filter with a permission-denied I/O error and allow other paths.
1210 /// - Assert `/allowed` returns OK and `/denied` returns `FORBIDDEN`.
1211 #[crate::rt_test]
1212 async fn test_app_filter_error() {
1213 let srv = init_service(
1214 App::new()
1215 .filter(async |req: WebRequest<()>| {
1216 if req.path() == "/denied" {
1217 Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied))
1218 } else {
1219 Ok(req)
1220 }
1221 })
1222 .route("/{tail}*", web::to(async || HttpResponse::Ok())),
1223 )
1224 .await;
1225 let resp = call_service(&srv, TestRequest::with_uri("/allowed").to_request()).await;
1226 assert_eq!(resp.status(), StatusCode::OK);
1227 let resp = call_service(&srv, TestRequest::with_uri("/denied").to_request()).await;
1228 assert_eq!(resp.status(), StatusCode::FORBIDDEN);
1229 }
1230}