forked from actix/actix-web
-
Notifications
You must be signed in to change notification settings - Fork 0
/
scope.rs
1156 lines (1035 loc) · 37.8 KB
/
scope.rs
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
use std::{cell::RefCell, fmt, future::Future, mem, rc::Rc};
use actix_http::Extensions;
use actix_router::{ResourceDef, Router};
use actix_service::{
apply, apply_fn_factory,
boxed::{self, BoxService, BoxServiceFactory},
IntoServiceFactory, Service, ServiceFactory, ServiceFactoryExt, Transform,
};
use futures_core::future::LocalBoxFuture;
use futures_util::future::join_all;
use crate::{
config::ServiceConfig,
data::Data,
dev::{AppService, HttpServiceFactory},
guard::Guard,
rmap::ResourceMap,
service::{AppServiceFactory, ServiceFactoryWrapper, ServiceRequest, ServiceResponse},
Error, Resource, Route,
};
type Guards = Vec<Box<dyn Guard>>;
type HttpService = BoxService<ServiceRequest, ServiceResponse, Error>;
type HttpNewService = BoxServiceFactory<(), ServiceRequest, ServiceResponse, Error, ()>;
/// Resources scope.
///
/// Scope is a set of resources with common root path.
/// Scopes collect multiple paths under a common path prefix.
/// Scope path can contain variable path segments as resources.
/// Scope prefix is always complete path segment, i.e `/app` would
/// be converted to a `/app/` and it would not match `/app` path.
///
/// You can get variable path segments from `HttpRequest::match_info()`.
/// `Path` extractor also is able to extract scope level variable segments.
///
/// ```
/// use actix_web::{web, App, HttpResponse};
///
/// fn main() {
/// let app = App::new().service(
/// web::scope("/{project_id}/")
/// .service(web::resource("/path1").to(|| async { HttpResponse::Ok() }))
/// .service(web::resource("/path2").route(web::get().to(|| HttpResponse::Ok())))
/// .service(web::resource("/path3").route(web::head().to(|| HttpResponse::MethodNotAllowed())))
/// );
/// }
/// ```
///
/// In the above example three routes get registered:
/// * /{project_id}/path1 - responds to all http method
/// * /{project_id}/path2 - `GET` requests
/// * /{project_id}/path3 - `HEAD` requests
pub struct Scope<T = ScopeEndpoint> {
endpoint: T,
rdef: String,
app_data: Option<Extensions>,
services: Vec<Box<dyn AppServiceFactory>>,
guards: Vec<Box<dyn Guard>>,
default: Option<Rc<HttpNewService>>,
external: Vec<ResourceDef>,
factory_ref: Rc<RefCell<Option<ScopeFactory>>>,
}
impl Scope {
/// Create a new scope
pub fn new(path: &str) -> Scope {
let factory_ref = Rc::new(RefCell::new(None));
Scope {
endpoint: ScopeEndpoint::new(Rc::clone(&factory_ref)),
rdef: path.to_string(),
app_data: None,
guards: Vec::new(),
services: Vec::new(),
default: None,
external: Vec::new(),
factory_ref,
}
}
}
impl<T> Scope<T>
where
T: ServiceFactory<
ServiceRequest,
Config = (),
Response = ServiceResponse,
Error = Error,
InitError = (),
>,
{
/// Add match guard to a scope.
///
/// ```
/// use actix_web::{web, guard, App, HttpRequest, HttpResponse};
///
/// async fn index(data: web::Path<(String, String)>) -> &'static str {
/// "Welcome!"
/// }
///
/// fn main() {
/// let app = App::new().service(
/// web::scope("/app")
/// .guard(guard::Header("content-type", "text/plain"))
/// .route("/test1", web::get().to(index))
/// .route("/test2", web::post().to(|r: HttpRequest| {
/// HttpResponse::MethodNotAllowed()
/// }))
/// );
/// }
/// ```
pub fn guard<G: Guard + 'static>(mut self, guard: G) -> Self {
self.guards.push(Box::new(guard));
self
}
/// Add scope data.
///
/// Data of different types from parent contexts will still be accessible. Any `Data<T>` types
/// set here can be extracted in handlers using the `Data<T>` extractor.
///
/// # Examples
/// ```
/// use std::cell::Cell;
/// use actix_web::{web, App, HttpRequest, HttpResponse, Responder};
///
/// struct MyData {
/// count: std::cell::Cell<usize>,
/// }
///
/// async fn handler(req: HttpRequest, counter: web::Data<MyData>) -> impl Responder {
/// // note this cannot use the Data<T> extractor because it was not added with it
/// let incr = *req.app_data::<usize>().unwrap();
/// assert_eq!(incr, 3);
///
/// // update counter using other value from app data
/// counter.count.set(counter.count.get() + incr);
///
/// HttpResponse::Ok().body(counter.count.get().to_string())
/// }
///
/// let app = App::new().service(
/// web::scope("/app")
/// .app_data(3usize)
/// .app_data(web::Data::new(MyData { count: Default::default() }))
/// .route("/", web::get().to(handler))
/// );
/// ```
pub fn app_data<U: 'static>(mut self, data: U) -> Self {
self.app_data
.get_or_insert_with(Extensions::new)
.insert(data);
self
}
/// Add scope data after wrapping in `Data<T>`.
///
/// Deprecated in favor of [`app_data`](Self::app_data).
#[deprecated(since = "4.0.0", note = "Use `.app_data(Data::new(val))` instead.")]
pub fn data<U: 'static>(self, data: U) -> Self {
self.app_data(Data::new(data))
}
/// Run external configuration as part of the scope building process.
///
/// This function is useful for moving parts of configuration to a different module or library.
/// For example, some of the resource's configuration could be moved to different module.
///
/// ```
/// use actix_web::{web, 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(|| HttpResponse::Ok()))
/// .route(web::head().to(|| HttpResponse::MethodNotAllowed()))
/// );
/// }
///
/// fn main() {
/// let app = App::new()
/// .wrap(middleware::Logger::default())
/// .service(
/// web::scope("/api")
/// .configure(config)
/// )
/// .route("/index.html", web::get().to(|| HttpResponse::Ok()));
/// }
/// ```
pub fn configure<F>(mut self, cfg_fn: F) -> Self
where
F: FnOnce(&mut ServiceConfig),
{
let mut cfg = ServiceConfig::new();
cfg_fn(&mut cfg);
self.services.extend(cfg.services);
self.external.extend(cfg.external);
// TODO: add Extensions::is_empty check and conditionally insert data
self.app_data
.get_or_insert_with(Extensions::new)
.extend(cfg.app_data);
self
}
/// Register HTTP service.
///
/// This is similar to `App's` service registration.
///
/// Actix Web provides several services implementations:
///
/// * *Resource* is an entry in resource table which corresponds to requested URL.
/// * *Scope* is a set of resources with common root path.
/// * "StaticFiles" is a service for static files support
///
/// ```
/// use actix_web::{web, App, HttpRequest};
///
/// struct AppState;
///
/// async fn index(req: HttpRequest) -> &'static str {
/// "Welcome!"
/// }
///
/// fn main() {
/// let app = App::new().service(
/// web::scope("/app").service(
/// web::scope("/v1")
/// .service(web::resource("/test1").to(index)))
/// );
/// }
/// ```
pub fn service<F>(mut self, factory: F) -> Self
where
F: HttpServiceFactory + 'static,
{
self.services
.push(Box::new(ServiceFactoryWrapper::new(factory)));
self
}
/// Configure route for a specific path.
///
/// This is a simplified version of the `Scope::service()` method.
/// This method can be called multiple times, in that case
/// multiple resources with one route would be registered for same resource path.
///
/// ```
/// use actix_web::{web, App, HttpResponse};
///
/// async fn index(data: web::Path<(String, String)>) -> &'static str {
/// "Welcome!"
/// }
///
/// fn main() {
/// let app = App::new().service(
/// web::scope("/app")
/// .route("/test1", web::get().to(index))
/// .route("/test2", web::post().to(|| HttpResponse::MethodNotAllowed()))
/// );
/// }
/// ```
pub fn route(self, path: &str, mut route: Route) -> Self {
self.service(
Resource::new(path)
.add_guards(route.take_guards())
.route(route),
)
}
/// Default service to be used if no matching route could be found.
///
/// If default resource is not registered, app's default resource is being used.
pub fn default_service<F, U>(mut self, f: F) -> Self
where
F: IntoServiceFactory<U, ServiceRequest>,
U: ServiceFactory<
ServiceRequest,
Config = (),
Response = ServiceResponse,
Error = Error,
> + 'static,
U::InitError: fmt::Debug,
{
// create and configure default resource
self.default = Some(Rc::new(boxed::factory(f.into_factory().map_init_err(
|e| log::error!("Can not construct default service: {:?}", e),
))));
self
}
/// Registers middleware, in the form of a middleware component (type),
/// that runs during inbound processing in the request
/// life-cycle (request -> response), modifying request as
/// necessary, across all requests managed by the *Scope*. Scope-level
/// middleware is more limited in what it can modify, relative to Route or
/// Application level middleware, in that Scope-level middleware can not modify
/// ServiceResponse.
///
/// Use middleware when you need to read or modify *every* request in some way.
pub fn wrap<M>(
self,
mw: M,
) -> Scope<
impl ServiceFactory<
ServiceRequest,
Config = (),
Response = ServiceResponse,
Error = Error,
InitError = (),
>,
>
where
M: Transform<
T::Service,
ServiceRequest,
Response = ServiceResponse,
Error = Error,
InitError = (),
>,
{
Scope {
endpoint: apply(mw, self.endpoint),
rdef: self.rdef,
app_data: self.app_data,
guards: self.guards,
services: self.services,
default: self.default,
external: self.external,
factory_ref: self.factory_ref,
}
}
/// Registers middleware, in the form of a closure, that runs during inbound
/// processing in the request life-cycle (request -> response), modifying
/// request as necessary, across all requests managed by the *Scope*.
/// Scope-level middleware is more limited in what it can modify, relative
/// to Route or Application level middleware, in that Scope-level middleware
/// can not modify ServiceResponse.
///
/// ```
/// use actix_service::Service;
/// use actix_web::{web, App};
/// use actix_web::http::{header::CONTENT_TYPE, HeaderValue};
///
/// async fn index() -> &'static str {
/// "Welcome!"
/// }
///
/// fn main() {
/// let app = App::new().service(
/// web::scope("/app")
/// .wrap_fn(|req, srv| {
/// let fut = srv.call(req);
/// async {
/// let mut res = fut.await?;
/// res.headers_mut().insert(
/// CONTENT_TYPE, HeaderValue::from_static("text/plain"),
/// );
/// Ok(res)
/// }
/// })
/// .route("/index.html", web::get().to(index)));
/// }
/// ```
pub fn wrap_fn<F, R>(
self,
mw: F,
) -> Scope<
impl ServiceFactory<
ServiceRequest,
Config = (),
Response = ServiceResponse,
Error = Error,
InitError = (),
>,
>
where
F: Fn(ServiceRequest, &T::Service) -> R + Clone,
R: Future<Output = Result<ServiceResponse, Error>>,
{
Scope {
endpoint: apply_fn_factory(self.endpoint, mw),
rdef: self.rdef,
app_data: self.app_data,
guards: self.guards,
services: self.services,
default: self.default,
external: self.external,
factory_ref: self.factory_ref,
}
}
}
impl<T> HttpServiceFactory for Scope<T>
where
T: ServiceFactory<
ServiceRequest,
Config = (),
Response = ServiceResponse,
Error = Error,
InitError = (),
> + 'static,
{
fn register(mut self, config: &mut AppService) {
// update default resource if needed
let default = self.default.unwrap_or_else(|| config.default_service());
// register nested services
let mut cfg = config.clone_config();
self.services
.into_iter()
.for_each(|mut srv| srv.register(&mut cfg));
let mut rmap = ResourceMap::new(ResourceDef::root_prefix(&self.rdef));
// external resources
for mut rdef in mem::take(&mut self.external) {
rmap.add(&mut rdef, None);
}
// complete scope pipeline creation
*self.factory_ref.borrow_mut() = Some(ScopeFactory {
default,
services: cfg
.into_services()
.1
.into_iter()
.map(|(mut rdef, srv, guards, nested)| {
rmap.add(&mut rdef, nested);
(rdef, srv, RefCell::new(guards))
})
.collect::<Vec<_>>()
.into_boxed_slice()
.into(),
});
// get guards
let guards = if self.guards.is_empty() {
None
} else {
Some(self.guards)
};
let scope_data = self.app_data.map(Rc::new);
// wraps endpoint service (including middleware) call and injects app data for this scope
let endpoint = apply_fn_factory(self.endpoint, move |mut req: ServiceRequest, srv| {
if let Some(ref data) = scope_data {
req.add_data_container(Rc::clone(data));
}
srv.call(req)
});
// register final service
config.register_service(
ResourceDef::root_prefix(&self.rdef),
guards,
endpoint,
Some(Rc::new(rmap)),
)
}
}
pub struct ScopeFactory {
services: Rc<[(ResourceDef, HttpNewService, RefCell<Option<Guards>>)]>,
default: Rc<HttpNewService>,
}
impl ServiceFactory<ServiceRequest> for ScopeFactory {
type Response = ServiceResponse;
type Error = Error;
type Config = ();
type Service = ScopeService;
type InitError = ();
type Future = LocalBoxFuture<'static, Result<Self::Service, Self::InitError>>;
fn new_service(&self, _: ()) -> Self::Future {
// construct default service factory future
let default_fut = self.default.new_service(());
// construct all services factory future with it's resource def and guards.
let factory_fut = join_all(self.services.iter().map(|(path, factory, guards)| {
let path = path.clone();
let guards = guards.borrow_mut().take();
let factory_fut = factory.new_service(());
async move {
let service = factory_fut.await?;
Ok((path, guards, service))
}
}));
Box::pin(async move {
let default = default_fut.await?;
// build router from the factory future result.
let router = factory_fut
.await
.into_iter()
.collect::<Result<Vec<_>, _>>()?
.drain(..)
.fold(Router::build(), |mut router, (path, guards, service)| {
router.rdef(path, service).2 = guards;
router
})
.finish();
Ok(ScopeService { router, default })
})
}
}
pub struct ScopeService {
router: Router<HttpService, Vec<Box<dyn Guard>>>,
default: HttpService,
}
impl Service<ServiceRequest> for ScopeService {
type Response = ServiceResponse;
type Error = Error;
type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
actix_service::always_ready!();
fn call(&self, mut req: ServiceRequest) -> Self::Future {
let res = self.router.recognize_checked(&mut req, |req, guards| {
if let Some(ref guards) = guards {
for f in guards {
if !f.check(req.head()) {
return false;
}
}
}
true
});
if let Some((srv, _info)) = res {
srv.call(req)
} else {
self.default.call(req)
}
}
}
#[doc(hidden)]
pub struct ScopeEndpoint {
factory: Rc<RefCell<Option<ScopeFactory>>>,
}
impl ScopeEndpoint {
fn new(factory: Rc<RefCell<Option<ScopeFactory>>>) -> Self {
ScopeEndpoint { factory }
}
}
impl ServiceFactory<ServiceRequest> for ScopeEndpoint {
type Response = ServiceResponse;
type Error = Error;
type Config = ();
type Service = ScopeService;
type InitError = ();
type Future = LocalBoxFuture<'static, Result<Self::Service, Self::InitError>>;
fn new_service(&self, _: ()) -> Self::Future {
self.factory.borrow_mut().as_mut().unwrap().new_service(())
}
}
#[cfg(test)]
mod tests {
use actix_service::Service;
use actix_utils::future::ok;
use bytes::Bytes;
use crate::{
dev::Body,
guard,
http::{header, HeaderValue, Method, StatusCode},
middleware::DefaultHeaders,
service::{ServiceRequest, ServiceResponse},
test::{call_service, init_service, read_body, TestRequest},
web, App, HttpMessage, HttpRequest, HttpResponse,
};
#[actix_rt::test]
async fn test_scope() {
let srv =
init_service(App::new().service(
web::scope("/app").service(web::resource("/path1").to(HttpResponse::Ok)),
))
.await;
let req = TestRequest::with_uri("/app/path1").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[actix_rt::test]
async fn test_scope_root() {
let srv = init_service(
App::new().service(
web::scope("/app")
.service(web::resource("").to(HttpResponse::Ok))
.service(web::resource("/").to(HttpResponse::Created)),
),
)
.await;
let req = TestRequest::with_uri("/app").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let req = TestRequest::with_uri("/app/").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
}
#[actix_rt::test]
async fn test_scope_root2() {
let srv = init_service(
App::new()
.service(web::scope("/app/").service(web::resource("").to(HttpResponse::Ok))),
)
.await;
let req = TestRequest::with_uri("/app").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
let req = TestRequest::with_uri("/app/").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[actix_rt::test]
async fn test_scope_root3() {
let srv = init_service(
App::new()
.service(web::scope("/app/").service(web::resource("/").to(HttpResponse::Ok))),
)
.await;
let req = TestRequest::with_uri("/app").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
let req = TestRequest::with_uri("/app/").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}
#[actix_rt::test]
async fn test_scope_route() {
let srv = init_service(
App::new().service(
web::scope("app")
.route("/path1", web::get().to(HttpResponse::Ok))
.route("/path1", web::delete().to(HttpResponse::Ok)),
),
)
.await;
let req = TestRequest::with_uri("/app/path1").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let req = TestRequest::with_uri("/app/path1")
.method(Method::DELETE)
.to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let req = TestRequest::with_uri("/app/path1")
.method(Method::POST)
.to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}
#[actix_rt::test]
async fn test_scope_route_without_leading_slash() {
let srv = init_service(
App::new().service(
web::scope("app").service(
web::resource("path1")
.route(web::get().to(HttpResponse::Ok))
.route(web::delete().to(HttpResponse::Ok)),
),
),
)
.await;
let req = TestRequest::with_uri("/app/path1").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let req = TestRequest::with_uri("/app/path1")
.method(Method::DELETE)
.to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let req = TestRequest::with_uri("/app/path1")
.method(Method::POST)
.to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
}
#[actix_rt::test]
async fn test_scope_guard() {
let srv = init_service(
App::new().service(
web::scope("/app")
.guard(guard::Get())
.service(web::resource("/path1").to(HttpResponse::Ok)),
),
)
.await;
let req = TestRequest::with_uri("/app/path1")
.method(Method::POST)
.to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
let req = TestRequest::with_uri("/app/path1")
.method(Method::GET)
.to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[actix_rt::test]
async fn test_scope_variable_segment() {
let srv = init_service(App::new().service(web::scope("/ab-{project}").service(
web::resource("/path1").to(|r: HttpRequest| {
HttpResponse::Ok().body(format!("project: {}", &r.match_info()["project"]))
}),
)))
.await;
let req = TestRequest::with_uri("/ab-project1/path1").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
match resp.response().body() {
Body::Bytes(ref b) => {
let bytes = b.clone();
assert_eq!(bytes, Bytes::from_static(b"project: project1"));
}
_ => panic!(),
}
let req = TestRequest::with_uri("/aa-project1/path1").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}
#[actix_rt::test]
async fn test_nested_scope() {
let srv = init_service(App::new().service(web::scope("/app").service(
web::scope("/t1").service(web::resource("/path1").to(HttpResponse::Created)),
)))
.await;
let req = TestRequest::with_uri("/app/t1/path1").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
}
#[actix_rt::test]
async fn test_nested_scope_no_slash() {
let srv = init_service(App::new().service(web::scope("/app").service(
web::scope("t1").service(web::resource("/path1").to(HttpResponse::Created)),
)))
.await;
let req = TestRequest::with_uri("/app/t1/path1").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
}
#[actix_rt::test]
async fn test_nested_scope_root() {
let srv = init_service(
App::new().service(
web::scope("/app").service(
web::scope("/t1")
.service(web::resource("").to(HttpResponse::Ok))
.service(web::resource("/").to(HttpResponse::Created)),
),
),
)
.await;
let req = TestRequest::with_uri("/app/t1").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let req = TestRequest::with_uri("/app/t1/").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
}
#[actix_rt::test]
async fn test_nested_scope_filter() {
let srv = init_service(
App::new().service(
web::scope("/app").service(
web::scope("/t1")
.guard(guard::Get())
.service(web::resource("/path1").to(HttpResponse::Ok)),
),
),
)
.await;
let req = TestRequest::with_uri("/app/t1/path1")
.method(Method::POST)
.to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
let req = TestRequest::with_uri("/app/t1/path1")
.method(Method::GET)
.to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[actix_rt::test]
async fn test_nested_scope_with_variable_segment() {
let srv = init_service(App::new().service(web::scope("/app").service(
web::scope("/{project_id}").service(web::resource("/path1").to(
|r: HttpRequest| {
HttpResponse::Created()
.body(format!("project: {}", &r.match_info()["project_id"]))
},
)),
)))
.await;
let req = TestRequest::with_uri("/app/project_1/path1").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
match resp.response().body() {
Body::Bytes(ref b) => {
let bytes = b.clone();
assert_eq!(bytes, Bytes::from_static(b"project: project_1"));
}
_ => panic!(),
}
}
#[actix_rt::test]
async fn test_nested2_scope_with_variable_segment() {
let srv = init_service(App::new().service(web::scope("/app").service(
web::scope("/{project}").service(web::scope("/{id}").service(
web::resource("/path1").to(|r: HttpRequest| {
HttpResponse::Created().body(format!(
"project: {} - {}",
&r.match_info()["project"],
&r.match_info()["id"],
))
}),
)),
)))
.await;
let req = TestRequest::with_uri("/app/test/1/path1").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::CREATED);
match resp.response().body() {
Body::Bytes(ref b) => {
let bytes = b.clone();
assert_eq!(bytes, Bytes::from_static(b"project: test - 1"));
}
_ => panic!(),
}
let req = TestRequest::with_uri("/app/test/1/path2").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}
#[actix_rt::test]
async fn test_default_resource() {
let srv = init_service(
App::new().service(
web::scope("/app")
.service(web::resource("/path1").to(HttpResponse::Ok))
.default_service(|r: ServiceRequest| {
ok(r.into_response(HttpResponse::BadRequest()))
}),
),
)
.await;
let req = TestRequest::with_uri("/app/path2").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let req = TestRequest::with_uri("/path2").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}
#[actix_rt::test]
async fn test_default_resource_propagation() {
let srv = init_service(
App::new()
.service(web::scope("/app1").default_service(web::to(HttpResponse::BadRequest)))
.service(web::scope("/app2"))
.default_service(|r: ServiceRequest| {
ok(r.into_response(HttpResponse::MethodNotAllowed()))
}),
)
.await;
let req = TestRequest::with_uri("/non-exist").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
let req = TestRequest::with_uri("/app1/non-exist").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let req = TestRequest::with_uri("/app2/non-exist").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
}
#[actix_rt::test]
async fn test_middleware() {
let srv = init_service(
App::new().service(
web::scope("app")
.wrap(
DefaultHeaders::new()
.header(header::CONTENT_TYPE, HeaderValue::from_static("0001")),
)
.service(web::resource("/test").route(web::get().to(HttpResponse::Ok))),
),
)
.await;
let req = TestRequest::with_uri("/app/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")
);
}
#[actix_rt::test]
async fn test_middleware_fn() {
let srv = init_service(
App::new().service(
web::scope("app")
.wrap_fn(|req, srv| {
let fut = srv.call(req);
async move {
let mut res = fut.await?;
res.headers_mut()
.insert(header::CONTENT_TYPE, HeaderValue::from_static("0001"));
Ok(res)
}
})
.route("/test", web::get().to(HttpResponse::Ok)),
),
)
.await;
let req = TestRequest::with_uri("/app/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")
);
}
#[actix_rt::test]
async fn test_middleware_app_data() {
let srv = init_service(
App::new().service(
web::scope("app")
.app_data(1usize)
.wrap_fn(|req, srv| {