Skip to content

Commit

Permalink
add GuardContext::header (#2569)
Browse files Browse the repository at this point in the history
  • Loading branch information
robjtede committed Jan 5, 2022
1 parent fe0bbfb commit 4ebf168
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 5 deletions.
8 changes: 6 additions & 2 deletions CHANGES.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
# Changes

## Unreleased - 2021-xx-xx
### Added
- `GuardContext::header` [#2569]

### Changed
- `HttpResponse` can now be used as a `Responder` with any body type.
- `HttpResponse` can now be used as a `Responder` with any body type. [#2567]

[#2501]: https://github.com/actix/actix-web/pull/2501
[#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
Expand Down
22 changes: 21 additions & 1 deletion src/guard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand All @@ -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::<header::Accept>() {
/// Some(hdr) => hdr.preference() == "image/*",
/// None => false,
/// }
/// });
/// ```
#[inline]
pub fn header<H: Header>(&self) -> Option<H> {
H::parse(self.req).ok()
}
}

/// Interface for routing guards.
Expand Down
4 changes: 2 additions & 2 deletions src/http/header/accept.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
///
Expand Down

0 comments on commit 4ebf168

Please sign in to comment.