From e6a7cfa1f51103bfc72f288a78838d28248688d9 Mon Sep 17 00:00:00 2001 From: ibraheemdev Date: Tue, 23 Mar 2021 09:27:58 -0400 Subject: [PATCH] add docs for header extractor --- src/http/header/mod.rs.html | 429 ------------------------------------ src/types/header.rs | 21 +- 2 files changed, 18 insertions(+), 432 deletions(-) delete mode 100644 src/http/header/mod.rs.html diff --git a/src/http/header/mod.rs.html b/src/http/header/mod.rs.html deleted file mode 100644 index 4a693142a..000000000 --- a/src/http/header/mod.rs.html +++ /dev/null @@ -1,429 +0,0 @@ - - - - -~/dev/rust/actix-web/src/http/header/mod.rs.html - - - - - - - - - - -
-  1 //! A Collection of Header implementations for common HTTP Headers.
-  2 //!
-  3 //! ## Mime
-  4 //!
-  5 //! Several header fields use MIME values for their contents. Keeping with the
-  6 //! strongly-typed theme, the [mime] crate
-  7 //! is used, such as `ContentType(pub Mime)`.
-  8 #![cfg_attr(rustfmt, rustfmt_skip)]
-  9 
- 10 pub use actix_http::http::header::*;
- 11 pub use self::accept_charset::AcceptCharset;
- 12 //pub use self::accept_encoding::AcceptEncoding;
- 13 pub use self::accept::Accept;
- 14 pub use self::accept_language::AcceptLanguage;
- 15 pub use self::allow::Allow;
- 16 pub use self::cache_control::{CacheControl, CacheDirective};
- 17 pub use self::content_disposition::{
- 18     ContentDisposition, DispositionParam, DispositionType,
- 19 };
- 20 pub use self::content_language::ContentLanguage;
- 21 pub use self::content_range::{ContentRange, ContentRangeSpec};
- 22 pub use self::content_type::ContentType;
- 23 pub use self::date::Date;
- 24 pub use self::etag::ETag;
- 25 pub use self::expires::Expires;
- 26 pub use self::if_match::IfMatch;
- 27 pub use self::if_modified_since::IfModifiedSince;
- 28 pub use self::if_none_match::IfNoneMatch;
- 29 pub use self::if_range::IfRange;
- 30 pub use self::if_unmodified_since::IfUnmodifiedSince;
- 31 pub use self::last_modified::LastModified;
- 32 //pub use self::range::{Range, ByteRangeSpec};
- 33 pub(crate) use self::utils::{fmt_comma_delimited, from_comma_delimited, from_one_raw_str};
- 34 
- 35 #[doc(hidden)]
- 36 #[macro_export]
- 37 macro_rules! __hyper__deref {
- 38     ($from:ty => $to:ty) => {
- 39         impl ::std::ops::Deref for $from {
- 40             type Target = $to;
- 41 
- 42             #[inline]
- 43             fn deref(&self) -> &$to {
- 44                 &self.0
- 45             }
- 46         }
- 47 
- 48         impl ::std::ops::DerefMut for $from {
- 49             #[inline]
- 50             fn deref_mut(&mut self) -> &mut $to {
- 51                 &mut self.0
- 52             }
- 53         }
- 54     };
- 55 }
- 56 
- 57 #[doc(hidden)]
- 58 #[macro_export]
- 59 macro_rules! __hyper__tm {
- 60     ($id:ident, $tm:ident{$($tf:item)*}) => {
- 61         #[allow(unused_imports)]
- 62         #[cfg(test)]
- 63         mod $tm{
- 64             use std::str;
- 65             use actix_http::http::Method;
- 66             use mime::*;
- 67             use $crate::http::header::*;
- 68             use super::$id as HeaderField;
- 69             $($tf)*
- 70         }
- 71 
- 72     }
- 73 }
- 74 
- 75 #[doc(hidden)]
- 76 #[macro_export]
- 77 macro_rules! test_header {
- 78     ($id:ident, $raw:expr) => {
- 79         #[test]
- 80         fn $id() {
- 81             use actix_http::test;
- 82 
- 83             let raw = $raw;
- 84             let a: Vec<Vec<u8>> = raw.iter().map(|x| x.to_vec()).collect();
- 85             let mut req = test::TestRequest::default();
- 86             for item in a {
- 87                 req = req.insert_header((HeaderField::name(), item)).take();
- 88             }
- 89             let req = req.finish();
- 90             let value = HeaderField::parse(&req);
- 91             let result = format!("{}", value.unwrap());
- 92             let expected = String::from_utf8(raw[0].to_vec()).unwrap();
- 93             let result_cmp: Vec<String> = result
- 94                 .to_ascii_lowercase()
- 95                 .split(' ')
- 96                 .map(|x| x.to_owned())
- 97                 .collect();
- 98             let expected_cmp: Vec<String> = expected
- 99                 .to_ascii_lowercase()
-100                 .split(' ')
-101                 .map(|x| x.to_owned())
-102                 .collect();
-103             assert_eq!(result_cmp.concat(), expected_cmp.concat());
-104         }
-105     };
-106     ($id:ident, $raw:expr, $typed:expr) => {
-107         #[test]
-108         fn $id() {
-109             use actix_http::test;
-110 
-111             let a: Vec<Vec<u8>> = $raw.iter().map(|x| x.to_vec()).collect();
-112             let mut req = test::TestRequest::default();
-113             for item in a {
-114                 req.insert_header((HeaderField::name(), item));
-115             }
-116             let req = req.finish();
-117             let val = HeaderField::parse(&req);
-118             let typed: Option<HeaderField> = $typed;
-119             // Test parsing
-120             assert_eq!(val.ok(), typed);
-121             // Test formatting
-122             if typed.is_some() {
-123                 let raw = &($raw)[..];
-124                 let mut iter = raw.iter().map(|b| str::from_utf8(&b[..]).unwrap());
-125                 let mut joined = String::new();
-126                 joined.push_str(iter.next().unwrap());
-127                 for s in iter {
-128                     joined.push_str(", ");
-129                     joined.push_str(s);
-130                 }
-131                 assert_eq!(format!("{}", typed.unwrap()), joined);
-132             }
-133         }
-134     };
-135 }
-136 
-137 #[doc(hidden)]
-138 #[macro_export]
-139 macro_rules! header {
-140     // $a:meta: Attributes associated with the header item (usually docs)
-141     // $id:ident: Identifier of the header
-142     // $n:expr: Lowercase name of the header
-143     // $nn:expr: Nice name of the header
-144 
-145     // List header, zero or more items
-146     ($(#[$a:meta])*($id:ident, $name:expr) => ($item:ty)*) => {
-147         $(#[$a])*
-148         #[derive(Clone, Debug, PartialEq)]
-149         pub struct $id(pub Vec<$item>);
-150         __hyper__deref!($id => Vec<$item>);
-151         impl $crate::http::header::Header for $id {
-152             #[inline]
-153             fn name() -> $crate::http::header::HeaderName {
-154                 $name
-155             }
-156             #[inline]
-157             fn parse<T>(msg: &T) -> Result<Self, $crate::error::ParseError>
-158                 where T: $crate::HttpMessage
-159             {
-160                 $crate::http::header::from_comma_delimited(
-161                     msg.headers().get_all(Self::name())).map($id)
-162             }
-163         }
-164         impl std::fmt::Display for $id {
-165             #[inline]
-166             fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> ::std::fmt::Result {
-167                 $crate::http::header::fmt_comma_delimited(f, &self.0[..])
-168             }
-169         }
-170         impl $crate::http::header::IntoHeaderValue for $id {
-171             type Error = $crate::http::header::InvalidHeaderValue;
-172 
-173             fn try_into_value(self) -> Result<$crate::http::header::HeaderValue, Self::Error> {
-174                 use std::fmt::Write;
-175                 let mut writer = $crate::http::header::Writer::new();
-176                 let _ = write!(&mut writer, "{}", self);
-177                 $crate::http::header::HeaderValue::from_maybe_shared(writer.take())
-178             }
-179         }
-180     };
-181     // List header, one or more items
-182     ($(#[$a:meta])*($id:ident, $name:expr) => ($item:ty)+) => {
-183         $(#[$a])*
-184         #[derive(Clone, Debug, PartialEq)]
-185         pub struct $id(pub Vec<$item>);
-186         __hyper__deref!($id => Vec<$item>);
-187         impl $crate::http::header::Header for $id {
-188             #[inline]
-189             fn name() -> $crate::http::header::HeaderName {
-190                 $name
-191             }
-192             #[inline]
-193             fn parse<T>(msg: &T) -> Result<Self, $crate::error::ParseError>
-194                 where T: $crate::HttpMessage
-195             {
-196                 $crate::http::header::from_comma_delimited(
-197                     msg.headers().get_all(Self::name())).map($id)
-198             }
-199         }
-200         impl std::fmt::Display for $id {
-201             #[inline]
-202             fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
-203                 $crate::http::header::fmt_comma_delimited(f, &self.0[..])
-204             }
-205         }
-206         impl $crate::http::header::IntoHeaderValue for $id {
-207             type Error = $crate::http::header::InvalidHeaderValue;
-208 
-209             fn try_into_value(self) -> Result<$crate::http::header::HeaderValue, Self::Error> {
-210                 use std::fmt::Write;
-211                 let mut writer = $crate::http::header::Writer::new();
-212                 let _ = write!(&mut writer, "{}", self);
-213                 $crate::http::header::HeaderValue::from_maybe_shared(writer.take())
-214             }
-215         }
-216     };
-217     // Single value header
-218     ($(#[$a:meta])*($id:ident, $name:expr) => [$value:ty]) => {
-219         $(#[$a])*
-220         #[derive(Clone, Debug, PartialEq)]
-221         pub struct $id(pub $value);
-222         __hyper__deref!($id => $value);
-223         impl $crate::http::header::Header for $id {
-224             #[inline]
-225             fn name() -> $crate::http::header::HeaderName {
-226                 $name
-227             }
-228             #[inline]
-229             fn parse<T>(msg: &T) -> Result<Self, $crate::error::ParseError>
-230                 where T: $crate::HttpMessage
-231             {
-232                 $crate::http::header::from_one_raw_str(
-233                     msg.headers().get(Self::name())).map($id)
-234             }
-235         }
-236         impl std::fmt::Display for $id {
-237             #[inline]
-238             fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
-239                 std::fmt::Display::fmt(&self.0, f)
-240             }
-241         }
-242         impl $crate::http::header::IntoHeaderValue for $id {
-243             type Error = $crate::http::header::InvalidHeaderValue;
-244 
-245             fn try_into_value(self) -> Result<$crate::http::header::HeaderValue, Self::Error> {
-246                 self.0.try_into_value()
-247             }
-248         }
-249     };
-250     // List header, one or more items with "*" option
-251     ($(#[$a:meta])*($id:ident, $name:expr) => {Any / ($item:ty)+}) => {
-252         $(#[$a])*
-253         #[derive(Clone, Debug, PartialEq)]
-254         pub enum $id {
-255             /// Any value is a match
-256             Any,
-257             /// Only the listed items are a match
-258             Items(Vec<$item>),
-259         }
-260         impl $crate::http::header::Header for $id {
-261             #[inline]
-262             fn name() -> $crate::http::header::HeaderName {
-263                 $name
-264             }
-265             #[inline]
-266             fn parse<T>(msg: &T) -> Result<Self, $crate::error::ParseError>
-267                 where T: $crate::HttpMessage
-268             {
-269                 let any = msg.headers().get(Self::name()).and_then(|hdr| {
-270                     hdr.to_str().ok().and_then(|hdr| Some(hdr.trim() == "*"))});
-271 
-272                 if let Some(true) = any {
-273                     Ok($id::Any)
-274                 } else {
-275                     Ok($id::Items(
-276                         $crate::http::header::from_comma_delimited(
-277                             msg.headers().get_all(Self::name()))?))
-278                 }
-279             }
-280         }
-281         impl std::fmt::Display for $id {
-282             #[inline]
-283             fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
-284                 match *self {
-285                     $id::Any => f.write_str("*"),
-286                     $id::Items(ref fields) => $crate::http::header::fmt_comma_delimited(
-287                         f, &fields[..])
-288                 }
-289             }
-290         }
-291         impl $crate::http::header::IntoHeaderValue for $id {
-292             type Error = $crate::http::header::InvalidHeaderValue;
-293 
-294             fn try_into_value(self) -> Result<$crate::http::header::HeaderValue, Self::Error> {
-295                 use std::fmt::Write;
-296                 let mut writer = $crate::http::header::Writer::new();
-297                 let _ = write!(&mut writer, "{}", self);
-298                 $crate::http::header::HeaderValue::from_maybe_shared(writer.take())
-299             }
-300         }
-301     };
-302 
-303     // optional test module
-304     ($(#[$a:meta])*($id:ident, $name:expr) => ($item:ty)* $tm:ident{$($tf:item)*}) => {
-305         header! {
-306             $(#[$a])*
-307             ($id, $name) => ($item)*
-308         }
-309 
-310         __hyper__tm! { $id, $tm { $($tf)* }}
-311     };
-312     ($(#[$a:meta])*($id:ident, $n:expr) => ($item:ty)+ $tm:ident{$($tf:item)*}) => {
-313         header! {
-314             $(#[$a])*
-315             ($id, $n) => ($item)+
-316         }
-317 
-318         __hyper__tm! { $id, $tm { $($tf)* }}
-319     };
-320     ($(#[$a:meta])*($id:ident, $name:expr) => [$item:ty] $tm:ident{$($tf:item)*}) => {
-321         header! {
-322             $(#[$a])* ($id, $name) => [$item]
-323         }
-324 
-325         __hyper__tm! { $id, $tm { $($tf)* }}
-326     };
-327     ($(#[$a:meta])*($id:ident, $name:expr) => {Any / ($item:ty)+} $tm:ident{$($tf:item)*}) => {
-328         header! {
-329             $(#[$a])*
-330             ($id, $name) => {Any / ($item)+}
-331         }
-332 
-333         __hyper__tm! { $id, $tm { $($tf)* }}
-334     };
-335 }
-336 
-337 mod accept_charset;
-338 // mod accept_encoding;
-339 mod accept;
-340 mod accept_language;
-341 mod allow;
-342 mod cache_control;
-343 mod content_disposition;
-344 mod content_language;
-345 mod content_range;
-346 mod content_type;
-347 mod date;
-348 mod etag;
-349 mod expires;
-350 mod if_match;
-351 mod if_modified_since;
-352 mod if_none_match;
-353 mod if_range;
-354 mod if_unmodified_since;
-355 mod last_modified;
-356 mod utils;
-
- - - diff --git a/src/types/header.rs b/src/types/header.rs index 66b206fff..b044aaa73 100644 --- a/src/types/header.rs +++ b/src/types/header.rs @@ -1,3 +1,5 @@ +//! For header extractor helper documentation, see [`Header`](crate::types::Header). + use std::{fmt, ops}; use futures_util::future::{err, ok, Ready}; @@ -8,11 +10,25 @@ use crate::extract::FromRequest; use crate::http::header::Header as ParseHeader; use crate::HttpRequest; -/// Header extractor and responder. +/// Extract typed headers from the request. +/// +/// To extract a header, the inner type `T` must implement the +/// [`Header`](crate::http::header::Header) trait. +/// +/// # Examples +/// ``` +/// use actix_web::{get, web, http::header}; +/// +/// #[get("/")] +/// async fn index(date: web::Header) -> String { +/// format!("Request was sent at {}", date.to_string()) +/// } +/// ``` +#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)] pub struct Header(pub T); impl Header { - /// Unwrap into inner `T` value. + /// Unwrap into the inner `T` value. pub fn into_inner(self) -> T { self.0 } @@ -50,7 +66,6 @@ where } } -/// See [here](#extractor) for example of usage as an extractor. impl FromRequest for Header where T: ParseHeader,