rama_http_headers/common/
access_control_request_method.rs

1use rama_http_types::{HeaderName, HeaderValue, Method};
2
3use crate::{Error, Header};
4
5/// `Access-Control-Request-Method` header, part of
6/// [CORS](http://www.w3.org/TR/cors/#access-control-request-method-request-header)
7///
8/// The `Access-Control-Request-Method` header indicates which method will be
9/// used in the actual request as part of the preflight request.
10/// # ABNF
11///
12/// ```text
13/// Access-Control-Request-Method: \"Access-Control-Request-Method\" \":\" Method
14/// ```
15///
16/// # Example values
17/// * `GET`
18///
19/// # Examples
20///
21/// ```
22/// use rama_http_headers::AccessControlRequestMethod;
23/// use rama_http_types::Method;
24///
25/// let req_method = AccessControlRequestMethod::from(Method::GET);
26/// ```
27#[derive(Clone, Debug, PartialEq, Eq, Hash)]
28pub struct AccessControlRequestMethod(Method);
29
30impl Header for AccessControlRequestMethod {
31    fn name() -> &'static HeaderName {
32        &::rama_http_types::header::ACCESS_CONTROL_REQUEST_METHOD
33    }
34
35    fn decode<'i, I: Iterator<Item = &'i HeaderValue>>(values: &mut I) -> Result<Self, Error> {
36        values
37            .next()
38            .and_then(|value| Method::from_bytes(value.as_bytes()).ok())
39            .map(AccessControlRequestMethod)
40            .ok_or_else(Error::invalid)
41    }
42
43    fn encode<E: Extend<HeaderValue>>(&self, values: &mut E) {
44        // For the more common methods, try to use a static string.
45        let s = match self.0 {
46            Method::GET => "GET",
47            Method::POST => "POST",
48            Method::PUT => "PUT",
49            Method::DELETE => "DELETE",
50            _ => {
51                let val = HeaderValue::from_str(self.0.as_ref())
52                    .expect("Methods are also valid HeaderValues");
53                values.extend(::std::iter::once(val));
54                return;
55            }
56        };
57
58        values.extend(::std::iter::once(HeaderValue::from_static(s)));
59    }
60}
61
62impl From<Method> for AccessControlRequestMethod {
63    fn from(method: Method) -> AccessControlRequestMethod {
64        AccessControlRequestMethod(method)
65    }
66}
67
68impl From<AccessControlRequestMethod> for Method {
69    fn from(method: AccessControlRequestMethod) -> Method {
70        method.0
71    }
72}