From 8fdf35895478b2ed5f08651e123922c012ae2937 Mon Sep 17 00:00:00 2001 From: Raphael C Date: Fri, 7 Jun 2024 16:31:53 +0200 Subject: [PATCH] Add app_data method to GuardContext (#3341) * changes: guard * fix(guard): docs link to app_data * docs: fix changelog --------- Co-authored-by: Rob Ede --- actix-web/CHANGES.md | 1 + actix-web/src/guard/mod.rs | 20 ++++++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/actix-web/CHANGES.md b/actix-web/CHANGES.md index e0390563cda..757fdce68bd 100644 --- a/actix-web/CHANGES.md +++ b/actix-web/CHANGES.md @@ -4,6 +4,7 @@ ### Added +- Add `guard::GuardContext::app_data()` method. - Implement `From>` for `Error`. ## 4.6.0 diff --git a/actix-web/src/guard/mod.rs b/actix-web/src/guard/mod.rs index 9451a60f903..41609953ad0 100644 --- a/actix-web/src/guard/mod.rs +++ b/actix-web/src/guard/mod.rs @@ -110,6 +110,12 @@ impl<'a> GuardContext<'a> { pub fn header(&self) -> Option { H::parse(self.req).ok() } + + /// Counterpart to [HttpRequest::app_data](crate::HttpRequest::app_data). + #[inline] + pub fn app_data(&self) -> Option<&T> { + self.req.app_data() + } } /// Interface for routing guards. @@ -512,4 +518,18 @@ mod tests { .to_srv_request(); assert!(guard.check(&req.guard_ctx())); } + + #[test] + fn app_data() { + const TEST_VALUE: u32 = 42; + let guard = fn_guard(|ctx| dbg!(ctx.app_data::()) == Some(&TEST_VALUE)); + + let req = TestRequest::default().app_data(TEST_VALUE).to_srv_request(); + assert!(guard.check(&req.guard_ctx())); + + let req = TestRequest::default() + .app_data(TEST_VALUE * 2) + .to_srv_request(); + assert!(!guard.check(&req.guard_ctx())); + } }