From 4ebf16890d2e3e45dd9f8352d5ddd712eafa6c47 Mon Sep 17 00:00:00 2001 From: Rob Ede Date: Wed, 5 Jan 2022 11:47:14 +0000 Subject: [PATCH] add `GuardContext::header` (#2569) --- CHANGES.md | 10 +++++++--- src/guard.rs | 22 +++++++++++++++++++++- src/http/header/accept.rs | 4 ++-- 3 files changed, 30 insertions(+), 6 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 922e0c7c..ec09de2a 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,10 +1,14 @@ # Changes ## Unreleased - 2021-xx-xx -### Changed -- `HttpResponse` can now be used as a `Responder` with any body type. +### Added +- `GuardContext::header` [#2569] -[#2501]: https://github.com/actix/actix-web/pull/2501 +### Changed +- `HttpResponse` can now be used as a `Responder` with any body type. [#2567] + +[#2567]: https://github.com/actix/actix-web/pull/2567 +[#2569]: https://github.com/actix/actix-web/pull/2569 ## 4.0.0-beta.19 - 2022-01-04 diff --git a/src/guard.rs b/src/guard.rs index 7a015d2d..f4200a38 100644 --- a/src/guard.rs +++ b/src/guard.rs @@ -54,7 +54,7 @@ use std::{ use actix_http::{header, uri::Uri, Extensions, Method as HttpMethod, RequestHead}; -use crate::service::ServiceRequest; +use crate::{http::header::Header, service::ServiceRequest}; /// Provides access to request parts that are useful during routing. #[derive(Debug)] @@ -80,6 +80,26 @@ impl<'a> GuardContext<'a> { pub fn req_data_mut(&self) -> RefMut<'a, Extensions> { self.req.req_data_mut() } + + /// Extracts a typed header from the request. + /// + /// Returns `None` if parsing `H` fails. + /// + /// # Examples + /// ``` + /// use actix_web::{guard::fn_guard, http::header}; + /// + /// let image_accept_guard = fn_guard(|ctx| { + /// match ctx.header::() { + /// Some(hdr) => hdr.preference() == "image/*", + /// None => false, + /// } + /// }); + /// ``` + #[inline] + pub fn header(&self) -> Option { + H::parse(self.req).ok() + } } /// Interface for routing guards. diff --git a/src/http/header/accept.rs b/src/http/header/accept.rs index 368a05bb..744c9b6e 100644 --- a/src/http/header/accept.rs +++ b/src/http/header/accept.rs @@ -2,10 +2,10 @@ use std::cmp::Ordering; use mime::Mime; -use super::QualityItem; +use super::{common_header, QualityItem}; use crate::http::header; -crate::http::header::common_header! { +common_header! { /// `Accept` header, defined /// in [RFC 7231 ยง5.3.2](https://datatracker.ietf.org/doc/html/rfc7231#section-5.3.2) ///