1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-06-12 18:29:34 +00:00
actix-web/src/http/header/cache_control.rs

259 lines
7.8 KiB
Rust
Raw Normal View History

2019-02-07 21:24:24 +00:00
use std::fmt::{self, Write};
use std::str::FromStr;
2021-04-16 19:28:21 +00:00
use super::{fmt_comma_delimited, from_comma_delimited, Header, IntoHeaderValue, Writer};
2019-02-07 21:24:24 +00:00
use crate::http::header;
/// `Cache-Control` header, defined
/// in [RFC 7234 §5.2](https://datatracker.ietf.org/doc/html/rfc7234#section-5.2).
2019-02-07 21:24:24 +00:00
///
/// The `Cache-Control` header field is used to specify directives for
/// caches along the request/response chain. Such cache directives are
/// unidirectional in that the presence of a directive in a request does
/// not imply that the same directive is to be given in the response.
///
/// # ABNF
/// ```text
/// Cache-Control = 1#cache-directive
/// cache-directive = token [ "=" ( token / quoted-string ) ]
/// ```
///
/// # Example Values
2019-02-07 21:24:24 +00:00
///
/// * `no-cache`
/// * `private, community="UCI"`
/// * `max-age=30`
///
/// # Examples
2021-01-15 02:11:10 +00:00
/// ```
/// use actix_web::HttpResponse;
/// use actix_web::http::header::{CacheControl, CacheDirective};
2019-02-07 21:24:24 +00:00
///
/// let mut builder = HttpResponse::Ok();
2021-01-15 02:11:10 +00:00
/// builder.insert_header(CacheControl(vec![CacheDirective::MaxAge(86400u32)]));
2019-02-07 21:24:24 +00:00
/// ```
///
/// ```
/// use actix_web::HttpResponse;
/// use actix_web::http::header::{CacheControl, CacheDirective};
2019-02-07 21:24:24 +00:00
///
/// let mut builder = HttpResponse::Ok();
2021-01-15 02:11:10 +00:00
/// builder.insert_header(CacheControl(vec![
2019-02-07 21:24:24 +00:00
/// CacheDirective::NoCache,
/// CacheDirective::Private,
/// CacheDirective::MaxAge(360u32),
/// CacheDirective::Extension("foo".to_owned(), Some("bar".to_owned())),
/// ]));
/// ```
#[derive(PartialEq, Clone, Debug)]
pub struct CacheControl(pub Vec<CacheDirective>);
2021-06-25 11:25:50 +00:00
crate::http::header::common_header_deref!(CacheControl => Vec<CacheDirective>);
2019-02-07 21:24:24 +00:00
2021-06-25 11:25:50 +00:00
// TODO: this could just be the crate::http::header::common_header! macro
2019-02-07 21:24:24 +00:00
impl Header for CacheControl {
fn name() -> header::HeaderName {
header::CACHE_CONTROL
}
#[inline]
fn parse<T>(msg: &T) -> Result<Self, crate::error::ParseError>
where
T: crate::HttpMessage,
{
let directives = from_comma_delimited(msg.headers().get_all(&Self::name()))?;
2019-02-07 21:24:24 +00:00
if !directives.is_empty() {
Ok(CacheControl(directives))
} else {
Err(crate::error::ParseError::Header)
}
}
}
impl fmt::Display for CacheControl {
2019-12-07 18:46:51 +00:00
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2021-04-15 21:05:06 +00:00
fmt_comma_delimited(f, &self.0[..])
2019-02-07 21:24:24 +00:00
}
}
impl IntoHeaderValue for CacheControl {
2019-12-05 17:35:43 +00:00
type Error = header::InvalidHeaderValue;
2019-02-07 21:24:24 +00:00
2021-01-15 02:11:10 +00:00
fn try_into_value(self) -> Result<header::HeaderValue, Self::Error> {
2019-02-07 21:24:24 +00:00
let mut writer = Writer::new();
let _ = write!(&mut writer, "{}", self);
2019-12-05 17:35:43 +00:00
header::HeaderValue::from_maybe_shared(writer.take())
2019-02-07 21:24:24 +00:00
}
}
/// `CacheControl` contains a list of these directives.
#[derive(PartialEq, Clone, Debug)]
pub enum CacheDirective {
/// "no-cache"
NoCache,
/// "no-store"
NoStore,
/// "no-transform"
NoTransform,
/// "only-if-cached"
OnlyIfCached,
// request directives
/// "max-age=delta"
MaxAge(u32),
/// "max-stale=delta"
MaxStale(u32),
/// "min-fresh=delta"
MinFresh(u32),
// response directives
/// "must-revalidate"
MustRevalidate,
/// "public"
Public,
/// "private"
Private,
/// "proxy-revalidate"
ProxyRevalidate,
/// "s-maxage=delta"
SMaxAge(u32),
/// Extension directives. Optionally include an argument.
Extension(String, Option<String>),
}
impl fmt::Display for CacheDirective {
2019-12-07 18:46:51 +00:00
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2019-02-07 21:24:24 +00:00
use self::CacheDirective::*;
fmt::Display::fmt(
match *self {
NoCache => "no-cache",
NoStore => "no-store",
NoTransform => "no-transform",
OnlyIfCached => "only-if-cached",
MaxAge(secs) => return write!(f, "max-age={}", secs),
MaxStale(secs) => return write!(f, "max-stale={}", secs),
MinFresh(secs) => return write!(f, "min-fresh={}", secs),
MustRevalidate => "must-revalidate",
Public => "public",
Private => "private",
ProxyRevalidate => "proxy-revalidate",
SMaxAge(secs) => return write!(f, "s-maxage={}", secs),
Extension(ref name, None) => &name[..],
Extension(ref name, Some(ref arg)) => {
return write!(f, "{}={}", name, arg);
}
},
f,
)
}
}
impl FromStr for CacheDirective {
type Err = Option<<u32 as FromStr>::Err>;
fn from_str(s: &str) -> Result<CacheDirective, Option<<u32 as FromStr>::Err>> {
use self::CacheDirective::*;
match s {
"no-cache" => Ok(NoCache),
"no-store" => Ok(NoStore),
"no-transform" => Ok(NoTransform),
"only-if-cached" => Ok(OnlyIfCached),
"must-revalidate" => Ok(MustRevalidate),
"public" => Ok(Public),
"private" => Ok(Private),
"proxy-revalidate" => Ok(ProxyRevalidate),
"" => Err(None),
_ => match s.find('=') {
Some(idx) if idx + 1 < s.len() => {
match (&s[..idx], (&s[idx + 1..]).trim_matches('"')) {
("max-age", secs) => secs.parse().map(MaxAge).map_err(Some),
("max-stale", secs) => secs.parse().map(MaxStale).map_err(Some),
("min-fresh", secs) => secs.parse().map(MinFresh).map_err(Some),
("s-maxage", secs) => secs.parse().map(SMaxAge).map_err(Some),
2021-04-16 19:28:21 +00:00
(left, right) => Ok(Extension(left.to_owned(), Some(right.to_owned()))),
2019-02-07 21:24:24 +00:00
}
}
Some(_) => Err(None),
None => Ok(Extension(s.to_owned(), None)),
},
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::http::header::Header;
use actix_http::test::TestRequest;
2019-02-07 21:24:24 +00:00
#[test]
fn test_parse_multiple_headers() {
2021-01-15 02:11:10 +00:00
let req = TestRequest::default()
.insert_header((header::CACHE_CONTROL, "no-cache, private"))
2019-02-07 21:24:24 +00:00
.finish();
let cache = Header::parse(&req);
assert_eq!(
cache.ok(),
Some(CacheControl(vec![
CacheDirective::NoCache,
CacheDirective::Private,
]))
)
}
#[test]
fn test_parse_argument() {
2021-01-15 02:11:10 +00:00
let req = TestRequest::default()
.insert_header((header::CACHE_CONTROL, "max-age=100, private"))
.finish();
2019-02-07 21:24:24 +00:00
let cache = Header::parse(&req);
assert_eq!(
cache.ok(),
Some(CacheControl(vec![
CacheDirective::MaxAge(100),
CacheDirective::Private,
]))
)
}
#[test]
fn test_parse_quote_form() {
2021-01-15 02:11:10 +00:00
let req = TestRequest::default()
.insert_header((header::CACHE_CONTROL, "max-age=\"200\""))
.finish();
2019-02-07 21:24:24 +00:00
let cache = Header::parse(&req);
assert_eq!(
cache.ok(),
Some(CacheControl(vec![CacheDirective::MaxAge(200)]))
)
}
#[test]
fn test_parse_extension() {
2021-01-15 02:11:10 +00:00
let req = TestRequest::default()
.insert_header((header::CACHE_CONTROL, "foo, bar=baz"))
.finish();
2019-02-07 21:24:24 +00:00
let cache = Header::parse(&req);
assert_eq!(
cache.ok(),
Some(CacheControl(vec![
CacheDirective::Extension("foo".to_owned(), None),
CacheDirective::Extension("bar".to_owned(), Some("baz".to_owned())),
]))
)
}
#[test]
fn test_parse_bad_syntax() {
2021-01-15 02:11:10 +00:00
let req = TestRequest::default()
.insert_header((header::CACHE_CONTROL, "foo="))
.finish();
2019-02-07 21:24:24 +00:00
let cache: Result<CacheControl, _> = Header::parse(&req);
assert_eq!(cache.ok(), None)
}
}