Skip to content

Commit b59d11f

Browse files
authored
Merge pull request #219 from http-rs/cache-age-header
Cache age header
2 parents c065bfd + 2e4771c commit b59d11f

File tree

2 files changed

+129
-0
lines changed

2 files changed

+129
-0
lines changed

src/cache/age.rs

Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
use crate::headers::{HeaderName, HeaderValue, Headers, ToHeaderValues, AGE};
2+
use crate::Status;
3+
4+
use std::fmt::Debug;
5+
use std::option;
6+
use std::time::Duration;
7+
8+
/// HTTP `Age` header
9+
///
10+
/// # Specifications
11+
///
12+
/// - [RFC 7234 Hypertext Transfer Protocol (HTTP/1.1): Caching](https://tools.ietf.org/html/rfc7234#section-5.1)
13+
///
14+
/// # Examples
15+
///
16+
/// ```
17+
/// # fn main() -> http_types::Result<()> {
18+
/// #
19+
/// use http_types::Response;
20+
/// use http_types::cache::Age;
21+
///
22+
/// let age = Age::from_secs(12);
23+
///
24+
/// let mut res = Response::new(200);
25+
/// age.apply(&mut res);
26+
///
27+
/// let age = Age::from_headers(res)?.unwrap();
28+
/// assert_eq!(age, Age::from_secs(12));
29+
/// #
30+
/// # Ok(()) }
31+
/// ```
32+
#[derive(Debug, Ord, PartialOrd, Eq, PartialEq)]
33+
pub struct Age {
34+
dur: Duration,
35+
}
36+
37+
impl Age {
38+
/// Create a new instance of `Age`.
39+
pub fn new(dur: Duration) -> Self {
40+
Self { dur }
41+
}
42+
43+
/// Create a new instance of `Age` from secs.
44+
pub fn from_secs(secs: u64) -> Self {
45+
let dur = Duration::from_secs(secs);
46+
Self { dur }
47+
}
48+
49+
/// Get the duration from the header.
50+
pub fn duration(&self) -> Duration {
51+
self.dur
52+
}
53+
54+
/// Create an instance of `Age` from a `Headers` instance.
55+
///
56+
/// # Implementation note
57+
///
58+
/// A header value of `"null"` is treated the same as if no header was sent.
59+
pub fn from_headers(headers: impl AsRef<Headers>) -> crate::Result<Option<Self>> {
60+
let headers = match headers.as_ref().get(AGE) {
61+
Some(headers) => headers,
62+
None => return Ok(None),
63+
};
64+
65+
// If we successfully parsed the header then there's always at least one
66+
// entry. We want the last entry.
67+
let header = headers.iter().last().unwrap();
68+
69+
let num: u64 = header.as_str().parse().status(400)?;
70+
let dur = Duration::from_secs_f64(num as f64);
71+
72+
Ok(Some(Self { dur }))
73+
}
74+
75+
/// Insert a `HeaderName` + `HeaderValue` pair into a `Headers` instance.
76+
pub fn apply(&self, mut headers: impl AsMut<Headers>) {
77+
headers.as_mut().insert(AGE, self.value());
78+
}
79+
80+
/// Get the `HeaderName`.
81+
pub fn name(&self) -> HeaderName {
82+
AGE
83+
}
84+
85+
/// Get the `HeaderValue`.
86+
pub fn value(&self) -> HeaderValue {
87+
let output = self.dur.as_secs().to_string();
88+
89+
// SAFETY: the internal string is validated to be ASCII.
90+
unsafe { HeaderValue::from_bytes_unchecked(output.into()) }
91+
}
92+
}
93+
94+
impl ToHeaderValues for Age {
95+
type Iter = option::IntoIter<HeaderValue>;
96+
fn to_header_values(&self) -> crate::Result<Self::Iter> {
97+
// A HeaderValue will always convert into itself.
98+
Ok(self.value().to_header_values().unwrap())
99+
}
100+
}
101+
102+
#[cfg(test)]
103+
mod test {
104+
use super::*;
105+
use crate::headers::Headers;
106+
107+
#[test]
108+
fn smoke() -> crate::Result<()> {
109+
let age = Age::new(Duration::from_secs(12));
110+
111+
let mut headers = Headers::new();
112+
age.apply(&mut headers);
113+
114+
let age = Age::from_headers(headers)?.unwrap();
115+
assert_eq!(age, Age::new(Duration::from_secs(12)));
116+
Ok(())
117+
}
118+
119+
#[test]
120+
fn bad_request_on_parse_error() -> crate::Result<()> {
121+
let mut headers = Headers::new();
122+
headers.insert(AGE, "<nori ate the tag. yum.>");
123+
let err = Age::from_headers(headers).unwrap_err();
124+
assert_eq!(err.status(), 400);
125+
Ok(())
126+
}
127+
}

src/cache/mod.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,9 @@
88
//!
99
//! - [MDN: HTTP Caching](https://developer.mozilla.org/en-US/docs/Web/HTTP/Caching)
1010
11+
mod age;
1112
mod cache_control;
1213

14+
pub use age::Age;
1315
pub use cache_control::CacheControl;
1416
pub use cache_control::CacheDirective;

0 commit comments

Comments
 (0)