tower_http/cors/
allow_headers.rs1use std::fmt;
2
3use http::{
4 header::{self, HeaderName, HeaderValue},
5 request::Parts as RequestParts,
6};
7
8use super::{separated_by_commas, Any, WILDCARD};
9
10#[derive(Clone, Default)]
17#[must_use]
18pub struct AllowHeaders(AllowHeadersInner);
19
20impl AllowHeaders {
21 pub fn any() -> Self {
27 Self(AllowHeadersInner::Const(Some(WILDCARD)))
28 }
29
30 pub fn list<I>(headers: I) -> Self
36 where
37 I: IntoIterator<Item = HeaderName>,
38 {
39 Self(AllowHeadersInner::Const(separated_by_commas(
40 headers.into_iter().map(Into::into),
41 )))
42 }
43
44 pub fn mirror_request() -> Self {
53 Self(AllowHeadersInner::MirrorRequest)
54 }
55
56 #[allow(clippy::borrow_interior_mutable_const)]
57 pub(super) fn is_wildcard(&self) -> bool {
58 matches!(&self.0, AllowHeadersInner::Const(Some(v)) if v == WILDCARD)
59 }
60
61 pub(super) fn varies_with_request_headers(&self) -> bool {
62 !matches!(&self.0, AllowHeadersInner::Const(_))
63 }
64
65 pub(super) fn to_header(&self, parts: &RequestParts) -> Option<(HeaderName, HeaderValue)> {
66 let allow_headers = match &self.0 {
67 AllowHeadersInner::Const(v) => v.clone()?,
68 AllowHeadersInner::MirrorRequest => parts
69 .headers
70 .get(header::ACCESS_CONTROL_REQUEST_HEADERS)?
71 .clone(),
72 };
73
74 Some((header::ACCESS_CONTROL_ALLOW_HEADERS, allow_headers))
75 }
76}
77
78impl fmt::Debug for AllowHeaders {
79 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80 match &self.0 {
81 AllowHeadersInner::Const(inner) => f.debug_tuple("Const").field(inner).finish(),
82 AllowHeadersInner::MirrorRequest => f.debug_tuple("MirrorRequest").finish(),
83 }
84 }
85}
86
87impl From<Any> for AllowHeaders {
88 fn from(_: Any) -> Self {
89 Self::any()
90 }
91}
92
93impl<const N: usize> From<[HeaderName; N]> for AllowHeaders {
94 fn from(arr: [HeaderName; N]) -> Self {
95 Self::list(arr)
96 }
97}
98
99impl From<Vec<HeaderName>> for AllowHeaders {
100 fn from(vec: Vec<HeaderName>) -> Self {
101 Self::list(vec)
102 }
103}
104
105#[derive(Clone)]
106enum AllowHeadersInner {
107 Const(Option<HeaderValue>),
108 MirrorRequest,
109}
110
111impl Default for AllowHeadersInner {
112 fn default() -> Self {
113 Self::Const(None)
114 }
115}