Expand description
Headers container, and common header fields.
§Why Typed?
Hyper has had the opinion that:
Headers should be strongly-typed, because that’s why we’re using Rust in the first place. Or, why not stringly-typed? Types give the following advantages:
- More difficult to typo, since typos in types should be caught by the compiler
- Parsing to a proper type by default
However, it seems that for many applications, it is sufficient to use
http::header::HeaderMap
(byte values) and parse only the headers that
are of interest.
§Parsing http::header::HeaderValue
s
HeaderValue
(s) implement the RawLike
trait which allows for parsing
with less copying than going through HeaderValue::to_str
or the Raw
type. See example usage below:
use http::header::{HeaderMap, CONTENT_ENCODING};
use hyperx::header::{ContentEncoding, Encoding, Header};
// Given a HeaderMap with 2 Content-Encoding headers and 3 delimited values
let mut hmap = HeaderMap::new();
hmap.insert(CONTENT_ENCODING, "chunked, gzip".parse()?);
hmap.append(CONTENT_ENCODING, "identity".parse()?);
// Parse the first header value
let first = hmap.get(CONTENT_ENCODING).unwrap();
let ce = ContentEncoding::parse_header(&first)?;
assert_eq!(ce, ContentEncoding(vec![Encoding::Chunked, Encoding::Gzip]));
// Parse all header values to a single list
let all = hmap.get_all(CONTENT_ENCODING);
let ce = ContentEncoding::parse_header(&all)?;
assert_eq!(ce, ContentEncoding(
vec![Encoding::Chunked, Encoding::Gzip, Encoding::Identity]
));
§TypedHeaders
extension to http::HeaderMap
The TypedHeaders
extension trait provides more
convenient encode
/decode
methods on HeaderMap
generically for the
standard header types named in the http crate:
use http::header::HeaderMap;
use hyperx::header::{ContentEncoding, Encoding, TypedHeaders};
let mut hmap = http::HeaderMap::new();
hmap.encode(
&ContentEncoding(vec![Encoding::Identity]));
hmap.encode_append(
&ContentEncoding(vec![Encoding::Gzip, Encoding::Chunked]));
let ce: ContentEncoding = hmap.decode()?;
assert_eq!(
*ce,
vec![Encoding::Identity, Encoding::Gzip, Encoding::Chunked]
);
§Defining Custom Headers
Hyperx provides all commonly used headers in HTTP. If you
need to define a custom header, it’s easy to do while still taking
advantage of the type system. Hyperx includes a header!
macro for
defining many wrapper-style headers.
header! { (XRequestGuid, "X-Request-Guid") => [String] }
fn main () {
let mut headers = http::HeaderMap::new();
headers.insert(
"x-request-guid",
XRequestGuid("a proper guid".to_owned()).to_string().parse().unwrap()
);
}
This works well for simple “string” headers. If you need more control, you can implement the trait directly.
§Implementing the Header
trait
Consider a Do Not Track header. It can be true or false, but it represents
that via the numerals 1
and 0
.
use std::fmt;
use hyperx::header::{self, Header, RawLike};
#[derive(Debug, Clone, Copy)]
struct Dnt(bool);
impl Header for Dnt {
fn header_name() -> &'static str {
"DNT"
}
fn parse_header<'a, T>(raw: &'a T) -> hyperx::Result<Dnt>
where T: RawLike<'a>
{
if let Some(line) = raw.one() {
if line.len() == 1 {
let byte = line[0];
match byte {
b'0' => return Ok(Dnt(true)),
b'1' => return Ok(Dnt(false)),
_ => ()
}
}
}
Err(hyperx::Error::Header)
}
fn fmt_header(&self, f: &mut header::Formatter) -> fmt::Result {
let value = if self.0 {
"1"
} else {
"0"
};
f.fmt_line(&value)
}
}
Modules§
- parsing
- Utility functions for Header implementations.
Macros§
- header
- Create a custom header type.
Structs§
- Accept
Accept
header, defined in RFC7231- Accept
Charset Accept-Charset
header, defined in RFC7231- Accept
Encoding Accept-Encoding
header, defined in RFC7231- Accept
Language Accept-Language
header, defined in RFC7231- Accept
Ranges Accept-Ranges
header, defined in RFC7233- Access
Control Allow Credentials Access-Control-Allow-Credentials
header, part of CORS- Access
Control Allow Headers Access-Control-Allow-Headers
header, part of CORS- Access
Control Allow Methods Access-Control-Allow-Methods
header, part of CORS- Access
Control Expose Headers Access-Control-Expose-Headers
header, part of CORS- Access
Control MaxAge Access-Control-Max-Age
header, part of CORS- Access
Control Request Headers Access-Control-Request-Headers
header, part of CORS- Access
Control Request Method Access-Control-Request-Method
header, part of CORS- Allow
Allow
header, defined in RFC7231- Authorization
Authorization
header, defined in RFC7235- Basic
- Credential holder for Basic Authentication
- Bearer
- Token holder for Bearer Authentication, most often seen with oauth
- Cache
Control Cache-Control
header, defined in RFC7234- Connection
Connection
header, defined in RFC7230- Content
Disposition - A
Content-Disposition
header, (re)defined in RFC6266. - Content
Encoding Content-Encoding
header, defined in RFC7231- Content
Language Content-Language
header, defined in RFC7231- Content
Length Content-Length
header, defined in RFC7230- Content
Location Content-Location
header, defined in RFC7231- Content
Range Content-Range
header, defined in RFC7233- Content
Type Content-Type
header, defined in RFC7231- Cookie
Cookie
header, defined in RFC6265- Cookie
Iter - Iterator for cookie.
- Date
Date
header, defined in RFC7231- ETag
ETag
header, defined in RFC7232- Entity
Tag - An entity tag, defined in RFC7232
- Expires
Expires
header, defined in RFC7234- Formatter
- A formatter used to serialize headers to an output stream.
- From
From
header, defined in RFC7231- Header
View - Returned with the
HeadersItems
iterator. - Headers
- A specialized map of typed headers.
- Headers
Items - An
Iterator
over the fields in aHeaders
map. - Host
- The
Host
header. - Http
Date - A timestamp with HTTP formatting and parsing
- IfModified
Since If-Modified-Since
header, defined in RFC7232- IfUnmodified
Since If-Unmodified-Since
header, defined in RFC7232- Language
Tag - A language tag as described in RFC 5646.
- Last
Event Id Last-Event-ID
header, defined in RFC3864- Last
Modified Last-Modified
header, defined in RFC7232- Link
- The
Link
header, defined in RFC5988 - Link
Value - A single
link-value
of aLink
header, based on: RFC5988 - Location
Location
header, defined in RFC7231- Origin
- The
Origin
header. - Prefer
Prefer
header, defined in RFC7240- Preference
Applied Preference-Applied
header, defined in RFC7240- Protocol
- Protocols that appear in the
Upgrade
header field - Proxy
Authorization Proxy-Authorization
header, defined in RFC7235- Quality
- Represents a quality used in quality values.
- Quality
Item - Represents an item with a quality value as defined in RFC7231.
- Raw
- A raw header value.
- Referer
Referer
header, defined in RFC7231- Server
Server
header, defined in RFC7231- SetCookie
Set-Cookie
header, defined RFC6265- Strict
Transport Security StrictTransportSecurity
header, defined in RFC6797- Te
TE
header, defined in RFC7230- Transfer
Encoding Transfer-Encoding
header, defined in RFC7230- Upgrade
Upgrade
header, defined in RFC7230- User
Agent User-Agent
header, defined in RFC7231- Value
MapIter - Iterator adaptor for HeaderValue
- Warning
Warning
header, defined in RFC7234
Enums§
- Access
Control Allow Origin - The
Access-Control-Allow-Origin
response header, part of CORS - Byte
Range Spec - Each
Range::Bytes
header can contain one or moreByteRangeSpecs
. EachByteRangeSpec
defines a range of bytes to fetch - Cache
Directive CacheControl
contains a list of these directives.- Charset
- A Mime charset.
- Connection
Option - Values that can be in the
Connection
header. - Content
Range Spec - Content-Range, described in RFC7233
- Disposition
Param - A parameter to the disposition type.
- Disposition
Type - The implied disposition of the content of the HTTP body.
- Encoding
- A value to represent an encoding used in
Transfer-Encoding
orAccept-Encoding
header. - Expect
- The
Expect
header. - IfMatch
If-Match
header, defined in RFC7232- IfNone
Match If-None-Match
header, defined in RFC7232- IfRange
If-Range
header, defined in RFC7233- Media
Desc - A Media Descriptors Enum based on: https://www.w3.org/TR/html401/types.html#h-6.13
- Pragma
- The
Pragma
header defined by HTTP/1.0. - Preference
- Prefer contains a list of these preferences.
- Protocol
Name - A protocol name used to identify a specific protocol. Names are case-sensitive
except for the
WebSocket
value. - Range
Range
header, defined in RFC7233- Range
Unit - Range Units, described in RFC7233
- Referrer
Policy Referrer-Policy
header, part of Referrer Policy- Relation
Type - A Link Relation Type Enum based on: RFC5988
- Retry
After - The
Retry-After
header. - Vary
Vary
header, defined in RFC7231
Traits§
- Header
- A trait for any object that will represent a header field and value.
- RawLike
- Trait for raw bytes parsing access to header values (aka lines) for a single header name.
- Scheme
- An Authorization scheme to be used in the header.
- Standard
Header - A trait for the “standard” headers that have an associated
HeaderName
constant in the http crate. - Typed
Headers - Extension trait for
decode
(parsing) andencode
(serialization) of typed headers from/to a collection of headers such ashttp::HeaderMap
.