1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
#![allow(clippy::new_without_default)]
use std::marker::PhantomData;
use crate::error::{Failure, IntoFailure};
use crate::http::{Request, Response};
use crate::router::ResourceDef;
use crate::service::{Identity, ServiceChainFactory, map_state_factory};
use crate::{Cfg, IntoServiceFactory, Middleware, Service, ServiceFactory, factory};
use super::app_service::{AppFactory, WebServiceRouter};
use super::config::{ServiceConfig, WebAppConfig};
use super::error::{WebError, WebResponseError};
use super::service::{AppServiceFactory, ServiceFactoryWrapper, WebServiceFactory};
use super::stack::{Filter, WebStack};
use super::{HttpService, Resource, Route, State, WebRequest, WebResponse};
/// The main builder for a web application.
///
/// Start with `App::new()` then add routes, resources,
/// scopes, middleware, filters, application state, and a fallback response.
///
/// Middleware and filters run before routing. ntex then chooses the resource
/// or scope that matches the request. If nothing matches, the application
/// returns `404 Not Found` unless you provide a custom fallback.
///
/// Add application-wide settings, such as middleware, filters,
/// [`App::with_config()`], and case-insensitive routing, before adding the
/// first route or service. After that, the builder becomes [`AppServices`],
/// where you can continue adding routes and services.
///
/// ```rust
/// use ntex::web::{self, middleware, App, HttpResponse};
///
/// App::default()
/// .middleware(middleware::Logger::default())
/// .service(
/// web::resource("/users")
/// .route(web::get().to(async || "users"))
/// .route(web::post().to(async || HttpResponse::Created())),
/// )
/// .default_service(
/// web::to(async || HttpResponse::NotFound().body("Not found")),
/// );
/// ```
#[derive(derive_more::Debug)]
#[debug("App")]
pub struct App<St: State, In = (), Out = In, M = Identity, F = Filter<St, In>> {
middleware: M,
filter: ServiceChainFactory<F, St, WebRequest<In>>,
external: Vec<ResourceDef>,
config: Option<Cfg<WebAppConfig>>,
case_insensitive: bool,
ph: PhantomData<Out>,
}
/// An application builder that already has routing configuration.
///
/// You usually do not need to name this type. It is returned naturally after
/// calling [`App::route()`], [`App::service()`], [`App::configure()`], or
/// [`App::default_service()`].
///
/// From here, you can add more routes and services or set the application
/// fallback. Return the finished builder from the factory passed to
/// [`web::server()`]. The [`AppServices::build()`] and
/// [`AppServices::build_with()`] methods are available when you need to
/// connect the application to a lower-level HTTP service yourself.
///
/// [`web::server()`]: super::server
#[derive(derive_more::Debug)]
#[debug("AppServices")]
pub struct AppServices<St: State, In, Out, M, F> {
middleware: M,
filter: ServiceChainFactory<F, St, WebRequest<In>>,
services: Vec<Box<dyn AppServiceFactory<St, Out>>>,
default: Option<HttpService<St, Out>>,
external: Vec<ResourceDef>,
config: Option<Cfg<WebAppConfig>>,
case_insensitive: bool,
ph: PhantomData<In>,
}
impl Default for App<()> {
fn default() -> Self {
App {
middleware: Identity,
filter: factory(Filter::new()),
config: None,
external: Vec::new(),
case_insensitive: false,
ph: PhantomData,
}
}
}
impl<St: State, In> App<St, In, In> {
/// Create application builder. Application can be configured with a builder-like pattern.
#[must_use]
pub fn new() -> Self {
App {
middleware: Identity,
filter: factory(Filter::new()),
config: None,
external: Vec::new(),
case_insensitive: false,
ph: PhantomData,
}
}
}
impl<St, In, Out, M, F> App<St, In, Out, M, F>
where
St: State,
In: 'static,
Out: 'static,
F: ServiceFactory<
St,
WebRequest<In>,
Res = WebRequest<Out>,
Error = WebError<St, St::Error>,
InitError = Failure,
>,
{
/// Run external configuration as part of the application building
/// process.
///
/// This function is useful for moving parts of configuration to a
/// different module or even library. For example,
/// some of the resource's configuration could be moved to different module.
///
/// ```rust,ignore
/// use ntex::web::{self, middleware, App, HttpResponse};
///
/// // this function could be located in different module
/// fn config(cfg: &mut web::ServiceConfig) {
/// cfg.service(web::resource("/test")
/// .route(web::get().to(async || { HttpResponse::Ok() }))
/// .route(web::head().to(async || { HttpResponse::MethodNotAllowed() }))
/// );
/// }
///
/// fn main() {
/// let app = App::default()
/// .middleware(middleware::Logger::default())
/// .configure(config) // <- register resources
/// .route("/index.html", web::get().to(async || { HttpResponse::Ok() }));
/// }
/// ```
#[must_use]
pub fn configure(
self,
f: impl FnOnce(&mut ServiceConfig<St, Out>),
) -> AppServices<St, In, Out, M, F> {
let mut cfg = ServiceConfig::new(self.external);
f(&mut cfg);
AppServices {
services: cfg.services,
default: None,
filter: self.filter,
middleware: self.middleware,
config: self.config,
external: cfg.external,
case_insensitive: self.case_insensitive,
ph: PhantomData,
}
}
/// Register a route for an application path.
///
/// This is shorthand for creating a [`Resource`] with one route and
/// registering it with [`App::service()`]. The route's method and custom
/// guards are promoted to resource guards.
///
/// Each call creates a separate resource, so the same path can be
/// registered more than once with different guards.
///
/// ```rust
/// use ntex::web::{self, App, HttpResponse};
///
/// App::default()
/// .route("/items", web::get().to(async || "list"))
/// .route("/items", web::post().to(async || HttpResponse::Created()));
/// ```
#[must_use]
pub fn route(self, path: &str, mut route: Route<St, Out>) -> AppServices<St, In, Out, M, F> {
self.service(
Resource::new(path)
.add_guards(route.take_guards())
.route(route),
)
}
/// Registers a web service with the application.
///
/// A service defines its own path and guards through [`WebServiceFactory`].
/// Common services include [`Resource`], [`Scope`](crate::web::Scope), handlers created with
/// route attribute macros, and custom services built with `web::service()`.
///
/// Use a resource to group several routes, filters, middleware, or a
/// fallback under one path. Use a scope to group services under a shared
/// path prefix.
///
/// If no registered service matches the request path and guards, the
/// application's default service is used.
///
/// ```rust
/// use ntex::web::{self, App, HttpResponse};
///
/// App::default()
/// .service(
/// web::resource("/users")
/// .route(web::get().to(async || "users"))
/// .route(web::post().to(async || HttpResponse::Created())),
/// )
/// .service(
/// web::scope("/api")
/// .route("/health", web::get().to(async || "OK")),
/// );
/// ```
#[must_use]
pub fn service<S>(self, factory: S) -> AppServices<St, In, Out, M, F>
where
S: WebServiceFactory<St, Out> + 'static,
{
AppServices {
services: vec![Box::new(ServiceFactoryWrapper::new(factory))],
default: None,
filter: self.filter,
middleware: self.middleware,
config: self.config,
external: self.external,
case_insensitive: self.case_insensitive,
ph: PhantomData,
}
}
/// Set the fallback service for unmatched application requests.
///
/// The fallback is called when no top-level resource or scope matches the
/// request path and guards. Without a custom fallback, the application
/// returns `404 Not Found`.
///
/// A matched resource or scope handles its own routing failures, so its
/// requests do not fall through to this service.
///
/// ```rust
/// use ntex::web::{self, App, HttpRequest, HttpResponse};
///
/// async fn not_found(req: HttpRequest) -> HttpResponse {
/// HttpResponse::NotFound()
/// .body(format!("No resource for {}", req.path()))
/// }
///
/// App::default()
/// .route("/health", web::get().to(async || "ready"))
/// .default_service(web::to(not_found));
/// ```
#[must_use]
pub fn default_service<U>(
self,
f: impl IntoServiceFactory<U, St, WebRequest<Out>>,
) -> AppServices<St, In, Out, M, F>
where
U: ServiceFactory<St, WebRequest<Out>, Res = WebResponse> + 'static,
U::Error: WebResponseError<St, St::Error>,
U::InitError: IntoFailure,
{
// create and configure default resource
let default = Some(HttpService::new(
f.into_factory()
.map_err(WebError::from_err)
.map_init_err(IntoFailure::fail),
));
AppServices {
default,
services: Vec::new(),
filter: self.filter,
middleware: self.middleware,
config: self.config,
external: self.external,
case_insensitive: self.case_insensitive,
ph: PhantomData,
}
}
/// Register an external resource.
///
/// External resources are useful for URL generation purposes only
/// and are never considered for matching at request time. Calls to
/// `HttpRequest::url_for()` will work as expected.
///
/// ```rust
/// use ntex::web::{self, App, HttpRequest, HttpResponse, error::UrlGenerationError};
///
/// async fn index(req: HttpRequest) -> Result<HttpResponse, UrlGenerationError> {
/// let url = req.url_for("youtube", &["asdlkjqme"])?;
/// assert_eq!(url.as_str(), "https://youtube.com/watch/asdlkjqme");
/// Ok(HttpResponse::Ok().into())
/// }
///
/// fn main() {
/// let app = App::default()
/// .external_resource("youtube", "https://youtube.com/watch/{video_id}")
/// .service(web::resource("/index.html").route(
/// web::get().to(index)));
/// }
/// ```
#[must_use]
pub fn external_resource(mut self, name: impl AsRef<str>, url: impl AsRef<str>) -> Self {
let mut rdef = ResourceDef::new(url.as_ref());
rdef.set_name(name.as_ref());
self.external.push(rdef);
self
}
/// Set the application's runtime configuration.
///
/// [`WebAppConfig`] contains connection metadata used by the application,
/// such as the host, secure-connection flag, local address, and request pool
/// size. It can also store typed configuration values with
/// [`WebAppConfig::set_state()`]; those values are available through
/// [`HttpRequest::app_state()`](crate::web::HttpRequest::app_state) and [`WebRequest::app_state()`].
///
/// Without an explicit configuration, each request uses the
/// [`WebAppConfig`] from its I/O context, or the default configuration if
/// the request has no associated I/O object. This method overrides that
/// selection for every request handled by this application.
///
/// This configuration is separate from the service-level application state
/// represented by `St`. To register routes and services from an external
/// function, use [`App::configure()`] instead.
///
/// ```rust
/// use ntex::web::{self, App, HttpRequest, WebAppConfig};
///
/// async fn index(req: HttpRequest) -> String {
/// let value = req.app_state::<usize>().copied().unwrap_or_default();
/// format!("Configured value: {value}")
/// }
///
/// let config = WebAppConfig::new()
/// .set_host("www.example.com".to_owned())
/// .set_secure()
/// .set_state(42usize);
///
/// App::default()
/// .with_config(config)
/// .route("/", web::get().to(index));
/// ```
#[must_use]
pub fn with_config(mut self, cfg: impl Into<Cfg<WebAppConfig>>) -> Self {
self.config = Some(cfg.into());
self
}
/// Registers a request filter.
///
/// Application filters run before the application router selects a
/// resource or scope. Filters are called in registration order, and each
/// filter receives the [`WebRequest`] returned by the previous one.
///
/// A filter can inspect or modify the request, or use
/// [`WebRequest::map_state()`] to change its request-local state type. It
/// must return another `WebRequest` to continue processing. Returning an
/// error stops the filter chain and prevents routing; the error is handled
/// through [`WebResponseError`].
///
/// Application middleware wraps the filter and router, so middleware runs
/// before filters on the inbound path.
///
/// ```rust
/// use std::convert::Infallible;
/// use ntex::web::{self, App, WebRequest};
///
/// async fn authenticate(
/// req: WebRequest<()>,
/// ) -> Result<WebRequest<&'static str>, Infallible> {
/// Ok(req.map_state(|()| "alice"))
/// }
///
/// async fn index(_state: &(), user: &'static str) -> String {
/// format!("Hello, {user}!")
/// }
///
/// App::new()
/// .filter(authenticate)
/// .route("/", web::get().to_with_state(index));
/// ```
#[must_use]
pub fn filter<Sf, R>(
self,
filter: impl IntoServiceFactory<Sf, St, WebRequest<Out>>,
) -> App<
St,
In,
R,
M,
impl ServiceFactory<
St,
WebRequest<In>,
Res = WebRequest<R>,
Error = WebError<St, St::Error>,
InitError = Failure,
>,
>
where
Sf: ServiceFactory<St, WebRequest<Out>, Res = WebRequest<R>>,
Sf::Error: WebResponseError<St, St::Error>,
Sf::InitError: IntoFailure,
{
App {
filter: self.filter.and_then(
filter
.into_factory()
.map_err(WebError::from_err)
.map_init_err(IntoFailure::fail),
),
middleware: self.middleware,
config: self.config,
external: self.external,
case_insensitive: self.case_insensitive,
ph: PhantomData,
}
}
/// Registers a middleware for this application.
///
/// Use application middleware for work that should apply to every request,
/// such as logging, response headers, or authentication. It runs before
/// the application filter and router on the way in, and can inspect or
/// modify the response on the way back.
///
/// Middleware may also return a response without calling the service it
/// wraps. In that case, the rest of the application pipeline is skipped.
///
/// Requests pass through middleware in the order it was added. Responses
/// travel back in the opposite order. In this example, `DefaultHeaders`
/// sees the request before `Logger`, while `Logger` sees the response
/// before `DefaultHeaders`.
///
/// Custom middleware should call the wrapped service through
/// [`Ctx::call()`](crate::Ctx::call) so readiness and lifecycle events are handled
/// correctly.
///
/// ```rust
/// use ntex::web::{self, middleware, App};
///
/// App::default()
/// .middleware(
/// middleware::DefaultHeaders::new()
/// .header("x-application", "example"),
/// )
/// .middleware(middleware::Logger::default())
/// .route("/", web::get().to(async || "Hello"));
/// ```
#[must_use]
pub fn middleware<U>(self, mw: U) -> App<St, In, Out, WebStack<St, U, M>, F> {
App {
middleware: WebStack::new(mw, self.middleware),
filter: self.filter,
config: self.config,
external: self.external,
case_insensitive: self.case_insensitive,
ph: PhantomData,
}
}
#[must_use]
/// Use ascii case-insensitive routing.
///
/// Only static segments could be case-insensitive.
pub fn case_insensitive_routing(mut self) -> Self {
self.case_insensitive = true;
self
}
}
impl<St, In, Out, M, F> AppServices<St, In, Out, M, F>
where
St: State,
Out: 'static,
F: ServiceFactory<
St,
WebRequest<In>,
Res = WebRequest<Out>,
Error = WebError<St, St::Error>,
InitError = Failure,
>,
{
/// Register a route for an application path.
///
/// This is shorthand for creating a [`Resource`] with one route and
/// registering it with [`AppServices::service()`]. The route's method and
/// custom guards are promoted to resource guards.
///
/// Consequently, if those guards reject a request, the generated resource
/// does not match and the application router continues searching. If
/// nothing else matches, the application default service is used. To use a
/// resource-level fallback such as the built-in `405 Method Not Allowed`,
/// register an explicit [`Resource`] and add routes with
/// [`Resource::route()`].
///
/// Each call creates a separate resource, so the same path can be
/// registered more than once with different guards.
///
/// ```rust
/// use ntex::web::{self, App, HttpResponse};
///
/// App::default()
/// .route("/items", web::get().to(async || "list"))
/// .route(
/// "/items",
/// web::post().to(async || HttpResponse::Created()),
/// );
/// ```
#[must_use]
pub fn route(self, path: &str, mut route: Route<St, Out>) -> Self {
self.service(
Resource::new(path)
.add_guards(route.take_guards())
.route(route),
)
}
/// Registers another web service with the application.
///
/// This has the same behavior as [`App::service()`]. The service supplies
/// its own path and guards and becomes part of the application's top-level
/// router.
///
/// If none of the registered services match, the application's default
/// service is used.
#[must_use]
pub fn service<S>(mut self, factory: S) -> Self
where
S: WebServiceFactory<St, Out> + 'static,
{
self.services
.push(Box::new(ServiceFactoryWrapper::new(factory)));
self
}
/// Set the fallback service for unmatched application requests.
///
/// The fallback is called when no top-level resource or scope matches the
/// request path and guards. Without a custom fallback, the application
/// returns `404 Not Found`.
///
/// A matched resource or scope handles its own routing failures, so its
/// requests do not fall through to this service.
///
/// ```rust
/// use ntex::web::{self, App, HttpRequest, HttpResponse};
///
/// async fn not_found(req: HttpRequest) -> HttpResponse {
/// HttpResponse::NotFound()
/// .body(format!("No resource for {}", req.path()))
/// }
///
/// App::default()
/// .route("/health", web::get().to(async || "ready"))
/// .default_service(web::to(not_found));
/// ```
#[must_use]
pub fn default_service<U>(mut self, f: impl IntoServiceFactory<U, St, WebRequest<Out>>) -> Self
where
U: ServiceFactory<St, WebRequest<Out>, Res = WebResponse> + 'static,
U::Error: WebResponseError<St, St::Error>,
U::InitError: IntoFailure,
{
// create and configure default resource
self.default = Some(HttpService::new(
f.into_factory()
.map_err(WebError::from_err)
.map_init_err(IntoFailure::fail),
));
self
}
}
impl<St, In, Out, M, F> AppServices<St, In, Out, M, F>
where
St: State,
In: 'static,
Out: 'static,
F: ServiceFactory<
St,
WebRequest<In>,
Res = WebRequest<Out>,
Error = WebError<St, St::Error>,
InitError = Failure,
>,
M: Middleware<WebServiceRouter<St, In, Out, F::Service>, St> + 'static,
M::Service: Service<St, WebRequest<()>, Res = WebResponse, Error = WebError<St, St::Error>>,
{
/// Builds the application into a service factory.
///
/// The returned factory accepts [`Request`] values and uses application
/// state supplied by the surrounding service pipeline. It can be passed to
/// [`HttpService`] when building an HTTP server manually.
///
/// Applications passed to [`web::server()`] do not normally need an
/// explicit call to `build()`.
///
/// ```rust
/// use ntex::web;
///
/// let factory = web::App::default()
/// .route("/", web::get().to(async || "Hello"))
/// .build();
/// ```
///
/// [`HttpService`]: crate::http::HttpService
/// [`web::server()`]: super::server
pub fn build(
self,
) -> impl ServiceFactory<
St,
Request,
Res = Response,
Error = WebError<St, St::Error>,
InitError = Failure,
> {
IntoServiceFactory::<AppFactory<St, In, Out, M, F>, St, Request>::into_factory(self)
}
}
impl<St, In, Out, M, F> AppServices<St, In, Out, M, F>
where
St: State,
In: 'static,
Out: 'static,
F: ServiceFactory<
St,
WebRequest<In>,
Res = WebRequest<Out>,
Error = WebError<St, St::Error>,
InitError = Failure,
>,
M: Middleware<WebServiceRouter<St, In, Out, F::Service>, St> + 'static,
M::Service: Service<St, WebRequest<()>, Res = WebResponse, Error = WebError<St, St::Error>>,
{
/// Builds the application with a fixed application state.
///
/// Unlike [`AppServices::build()`], which takes its application state from
/// the surrounding service pipeline, this method stores `state` in the
/// returned factory. Web handlers, filters, middleware, and services use
/// this fixed state even when the outer pipeline uses a different state
/// type.
///
/// ```rust
/// use ntex::web;
///
/// #[derive(Clone)]
/// struct AppState {
/// greeting: &'static str,
/// }
///
/// impl web::State for AppState {
/// type Error = web::DefaultError;
/// }
///
/// async fn index(state: &AppState, _request_state: ()) -> String {
/// state.greeting.to_owned()
/// }
///
/// let app = web::App::<AppState>::new()
/// .route("/", web::get().to_with_state(index))
/// .build_with::<()>(AppState { greeting: "Hello" });
/// ```
pub fn build_with<Outer>(
self,
state: St,
) -> impl ServiceFactory<
Outer,
Request,
Res = Response,
Error = WebError<St, St::Error>,
InitError = Failure,
>
where
St: Clone,
{
map_state_factory(
state,
IntoServiceFactory::<AppFactory<St, In, Out, M, F>, St, Request>::into_factory(self),
)
}
}
impl<St, In, Out, M, F> IntoServiceFactory<AppFactory<St, In, Out, M, F>, St, Request>
for AppServices<St, In, Out, M, F>
where
St: State,
In: 'static,
Out: 'static,
F: ServiceFactory<
St,
WebRequest<In>,
Res = WebRequest<Out>,
Error = WebError<St, St::Error>,
InitError = Failure,
>,
M: Middleware<WebServiceRouter<St, In, Out, F::Service>, St> + 'static,
M::Service: Service<St, WebRequest<()>, Res = WebResponse, Error = WebError<St, St::Error>>,
{
fn into_factory(self) -> AppFactory<St, In, Out, M, F> {
AppFactory::new(
self.middleware,
self.filter,
self.services,
self.default,
self.config,
self.external,
self.case_insensitive,
)
}
}
#[cfg(test)]
mod tests {
use std::{cell::Cell, convert::Infallible, rc::Rc};
use super::*;
use crate::http::{Method, StatusCode, header, header::HeaderValue};
use crate::web::test::{TestRequest, call_service, init_service, read_body};
use crate::web::{self, HttpRequest, HttpResponse, middleware::DefaultHeaders};
#[crate::rt_test]
async fn test_default_resource() {
let srv = App::new()
.service(web::resource("/test").to(async || HttpResponse::Ok()))
.build()
.pipeline(())
.await
.unwrap();
let req = TestRequest::with_uri("/test").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let req = TestRequest::with_uri("/blah").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
let srv = App::new()
.service(web::resource("/test").to(async || HttpResponse::Ok()))
.service(
web::resource("/test2")
.default_service(async move |r: WebRequest<()>| {
Ok::<_, Infallible>(r.into_response(HttpResponse::Created()))
})
.route(web::get().to(async || HttpResponse::Ok())),
)
.default_service(async move |r: WebRequest<()>| {
Ok::<_, Infallible>(r.into_response(HttpResponse::MethodNotAllowed()))
})
.build()
.pipeline(())
.await
.unwrap();
let req = TestRequest::with_uri("/blah").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
let req = TestRequest::with_uri("/test2").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let req = TestRequest::with_uri("/test2")
.method(Method::POST)
.to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
}
#[crate::rt_test]
async fn test_filter() {
let filter = Rc::new(Cell::new(false));
let filter2 = filter.clone();
let srv = init_service(
App::new()
.filter(async move |req: WebRequest<()>| {
filter2.set(true);
Ok::<_, Infallible>(req)
})
.route("/test", web::get().to(async || HttpResponse::Ok())),
)
.await;
let req = TestRequest::with_uri("/test").to_request();
let resp = call_service(&srv, req).await;
assert_eq!(resp.status(), StatusCode::OK);
assert!(filter.get());
}
#[crate::rt_test]
async fn test_wrap() {
let srv = init_service(
App::new()
.middleware(
DefaultHeaders::new()
.header(header::CONTENT_TYPE, HeaderValue::from_static("0001")),
)
.route("/test", web::get().to(async || HttpResponse::Ok())),
)
.await;
let req = TestRequest::with_uri("/test").to_request();
let resp = call_service(&srv, req).await;
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(
resp.headers().get(header::CONTENT_TYPE).unwrap(),
HeaderValue::from_static("0001")
);
}
#[crate::rt_test]
async fn test_router_wrap() {
let srv = init_service(
App::new()
.middleware(
DefaultHeaders::new()
.header(header::CONTENT_TYPE, HeaderValue::from_static("0001")),
)
.route("/test", web::get().to(async || HttpResponse::Ok())),
)
.await;
let req = TestRequest::with_uri("/test").to_request();
let resp = call_service(&srv, req).await;
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(
resp.headers().get(header::CONTENT_TYPE).unwrap(),
HeaderValue::from_static("0001")
);
}
#[crate::rt_test]
async fn test_case_insensitive_router() {
let srv = init_service(
App::new()
.case_insensitive_routing()
.route("/test", web::get().to(async || HttpResponse::Ok())),
)
.await;
let req = TestRequest::with_uri("/test").to_request();
let resp = call_service(&srv, req).await;
assert_eq!(resp.status(), StatusCode::OK);
let req = TestRequest::with_uri("/Test").to_request();
let resp = call_service(&srv, req).await;
assert_eq!(resp.status(), StatusCode::OK);
}
#[crate::rt_test]
async fn test_extension() {
let cfg = WebAppConfig::new().set_state(10usize);
let srv = init_service(
App::new()
.with_config(cfg)
.filter(async move |req: WebRequest<()>| {
assert_eq!(*req.app_state::<usize>().unwrap(), 10);
Ok::<_, Infallible>(req)
})
.service(web::resource("/").to(async move |req: HttpRequest| {
assert_eq!(*req.app_state::<usize>().unwrap(), 10);
HttpResponse::Ok()
})),
)
.await;
let req = TestRequest::default().to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[crate::rt_test]
async fn test_external_resource() {
use crate::util::Bytes;
let srv = init_service(
App::new()
.external_resource("youtube", "https://youtube.com/watch/{video_id}")
.route(
"/test",
web::get().to(async move |req: HttpRequest| {
HttpResponse::Ok()
.body(format!("{}", req.url_for("youtube", ["12345"]).unwrap()))
}),
),
)
.await;
let req = TestRequest::with_uri("/test").to_request();
let resp = call_service(&srv, req).await;
assert_eq!(resp.status(), StatusCode::OK);
let body = read_body(resp).await;
assert_eq!(body, Bytes::from_static(b"https://youtube.com/watch/12345"));
}
#[crate::rt_test]
async fn test_pooled_request_resource_map() {
use crate::util::Bytes;
async fn url(req: HttpRequest) -> HttpResponse {
HttpResponse::Ok().body(format!("{}", req.url_for("docs", ["1"]).unwrap()))
}
let srv1 = init_service(
App::new()
.external_resource("docs", "https://one.example.com/{page}")
.route("/test", web::get().to(url)),
)
.await;
let srv2 = init_service(
App::new()
.external_resource("docs", "https://two.example.com/{page}")
.route("/test", web::get().to(url)),
)
.await;
for _ in 0..2 {
for (srv, expected) in [
(&srv1, &b"https://one.example.com/1"[..]),
(&srv2, &b"https://two.example.com/1"[..]),
] {
let req = TestRequest::with_uri("/test").to_request();
let resp = call_service(srv, req).await;
assert_eq!(read_body(resp).await, Bytes::from_static(expected));
}
}
}
#[crate::rt_test]
async fn test_app_default_service() {
let srv =
init_service(App::default().default_service(web::to(async || HttpResponse::Created())))
.await;
let resp = call_service(&srv, TestRequest::with_uri("/any").to_request()).await;
assert_eq!(resp.status(), StatusCode::CREATED);
srv.shutdown().await;
}
#[crate::rt_test]
async fn test_app_service_init_errors() {
use crate::service::{fn_factory, fn_service};
let attempts = Rc::new(Cell::new(0));
let attempts2 = attempts.clone();
let failing = move || {
let attempts = attempts2.clone();
fn_factory(async move |(): &()| {
attempts.set(attempts.get() + 1);
if attempts.get() % 2 == 1 {
Err(std::io::Error::other("init error"))
} else {
Ok(fn_service(async |req: WebRequest<()>| {
Ok::<_, Infallible>(req.into_response(HttpResponse::Ok()))
}))
}
})
};
let srv = init_service(
App::new()
.service(web::service("/test").build(failing()))
.default_service(failing()),
)
.await;
// failed services are not cached, next request creates them again
for path in ["/test", "/unknown"] {
let resp = call_service(&srv, TestRequest::with_uri(path).to_request()).await;
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
let resp = call_service(&srv, TestRequest::with_uri(path).to_request()).await;
assert_eq!(resp.status(), StatusCode::OK);
let resp = call_service(&srv, TestRequest::with_uri(path).to_request()).await;
assert_eq!(resp.status(), StatusCode::OK);
}
assert_eq!(attempts.get(), 4);
}
#[crate::rt_test]
async fn test_app_filter_error() {
let srv = init_service(
App::new()
.filter(async |req: WebRequest<()>| {
if req.path() == "/denied" {
Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied))
} else {
Ok(req)
}
})
.route("/{tail}*", web::to(async || HttpResponse::Ok())),
)
.await;
let resp = call_service(&srv, TestRequest::with_uri("/allowed").to_request()).await;
assert_eq!(resp.status(), StatusCode::OK);
let resp = call_service(&srv, TestRequest::with_uri("/denied").to_request()).await;
assert_eq!(resp.status(), StatusCode::FORBIDDEN);
}
}