From 548f6f89bf95bc2e2475074c33221768a1d1515e Mon Sep 17 00:00:00 2001 From: Nikolay Kim Date: Sat, 23 Mar 2019 21:39:02 -0700 Subject: [PATCH] allow to get app data via HttpRequest --- src/request.rs | 47 +++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 45 insertions(+), 2 deletions(-) diff --git a/src/request.rs b/src/request.rs index 1722925f8..33b63acd7 100644 --- a/src/request.rs +++ b/src/request.rs @@ -8,6 +8,7 @@ use actix_http::{Error, Extensions, HttpMessage, Message, Payload, RequestHead}; use actix_router::{Path, Url}; use crate::config::AppConfig; +use crate::data::Data; use crate::error::UrlGenerationError; use crate::extract::FromRequest; use crate::info::ConnectionInfo; @@ -100,6 +101,16 @@ impl HttpRequest { &self.config } + /// Get an application data stored with `App::data()` method during + /// application configuration. + pub fn app_data(&self) -> Option> { + if let Some(st) = self.config.extensions().get::>() { + Some(st.clone()) + } else { + None + } + } + /// Generate url for named resource /// /// ```rust @@ -239,8 +250,9 @@ impl fmt::Debug for HttpRequest { mod tests { use super::*; use crate::dev::{ResourceDef, ResourceMap}; - use crate::http::header; - use crate::test::TestRequest; + use crate::http::{header, StatusCode}; + use crate::test::{call_success, init_service, TestRequest}; + use crate::{web, App, HttpResponse}; #[test] fn test_debug() { @@ -356,4 +368,35 @@ mod tests { "https://youtube.com/watch/oHg5SJYRHA0" ); } + + #[test] + fn test_app_data() { + let mut srv = init_service(App::new().data(10usize).service( + web::resource("/").to(|req: HttpRequest| { + if req.app_data::().is_some() { + HttpResponse::Ok() + } else { + HttpResponse::BadRequest() + } + }), + )); + + let req = TestRequest::default().to_request(); + let resp = call_success(&mut srv, req); + assert_eq!(resp.status(), StatusCode::OK); + + let mut srv = init_service(App::new().data(10u32).service( + web::resource("/").to(|req: HttpRequest| { + if req.app_data::().is_some() { + HttpResponse::Ok() + } else { + HttpResponse::BadRequest() + } + }), + )); + + let req = TestRequest::default().to_request(); + let resp = call_success(&mut srv, req); + assert_eq!(resp.status(), StatusCode::BAD_REQUEST); + } }