From 9a26ee56fa7756c7b64c58c6ef5b73fe6ce72a28 Mon Sep 17 00:00:00 2001 From: Augusto Date: Mon, 26 Oct 2020 14:11:27 +0100 Subject: [PATCH] Adding app_data to ServiceConfig (#1757) --- actix-http/src/extensions.rs | 5 +++++ src/app.rs | 1 + src/config.rs | 19 ++++++++++++++++++- 3 files changed, 24 insertions(+), 1 deletion(-) diff --git a/actix-http/src/extensions.rs b/actix-http/src/extensions.rs index 96e01767b..22314e4ac 100644 --- a/actix-http/src/extensions.rs +++ b/actix-http/src/extensions.rs @@ -61,6 +61,11 @@ impl Extensions { pub fn clear(&mut self) { self.map.clear(); } + + /// Extends it with the content for another `Extensions` + pub fn extend(&mut self, extensions: Extensions) { + self.map.extend(extensions.map); + } } impl fmt::Debug for Extensions { diff --git a/src/app.rs b/src/app.rs index 6a4b97b69..8dd86f7ec 100644 --- a/src/app.rs +++ b/src/app.rs @@ -183,6 +183,7 @@ where self.data.extend(cfg.data); self.services.extend(cfg.services); self.external.extend(cfg.external); + self.extensions.extend(cfg.extensions); self } diff --git a/src/config.rs b/src/config.rs index f7bebb4c5..20da72ac7 100644 --- a/src/config.rs +++ b/src/config.rs @@ -178,6 +178,7 @@ pub struct ServiceConfig { pub(crate) services: Vec>, pub(crate) data: Vec>, pub(crate) external: Vec, + pub(crate) extensions: Extensions, } impl ServiceConfig { @@ -186,6 +187,7 @@ impl ServiceConfig { services: Vec::new(), data: Vec::new(), external: Vec::new(), + extensions: Extensions::new(), } } @@ -198,6 +200,17 @@ impl ServiceConfig { self } + /// Set application level arbitrary data item. + /// + /// Application data stored with `App::app_data()` method is available + /// via `HttpRequest::app_data()` method at runtime. + /// + /// Note: this method is ignored for `Scope::configure` method + pub fn app_data(&mut self, ext: U) -> &mut Self { + self.extensions.insert(ext); + self + } + /// Configure route for a specific path. /// /// This is same as `App::route()` method. @@ -254,11 +267,15 @@ mod tests { async fn test_data() { let cfg = |cfg: &mut ServiceConfig| { cfg.data(10usize); + cfg.app_data(10usize); }; let mut srv = init_service(App::new().configure(cfg).service( - web::resource("/").to(|_: web::Data| HttpResponse::Ok()), + web::resource("/").to(|_: web::Data, req: HttpRequest| { + assert_eq!(*req.app_data::().unwrap(), 10usize); + HttpResponse::Ok() + }), )) .await; let req = TestRequest::default().to_request();