rama_http/headers/forwarded/
mod.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
pub use rama_net::forwarded::Forwarded;
use rama_net::forwarded::ForwardedElement;

mod via;
#[doc(inline)]
pub use via::Via;

mod x_forwarded_for;
#[doc(inline)]
pub use x_forwarded_for::XForwardedFor;

mod x_forwarded_host;
#[doc(inline)]
pub use x_forwarded_host::XForwardedHost;

mod x_forwarded_proto;
#[doc(inline)]
pub use x_forwarded_proto::XForwardedProto;

mod exotic_forward_ip;
#[doc(inline)]
pub use exotic_forward_ip::{CFConnectingIp, ClientIp, TrueClientIp, XClientIp, XRealIp};

/// A trait for types headers that is used by middleware
/// which supports headers that can be converted into and from Forward data.
pub trait ForwardHeader: crate::headers::Header + IntoIterator<Item = ForwardedElement> {
    /// Try to convert the given iterator of `ForwardedElement` into the header.
    ///
    /// `None` is returned if the conversion fails.
    fn try_from_forwarded<'a, I>(into_it: I) -> Option<Self>
    where
        I: IntoIterator<Item = &'a ForwardedElement>,
        Self: Sized;
}

impl ForwardHeader for Forwarded {
    fn try_from_forwarded<'a, I>(input: I) -> Option<Self>
    where
        I: IntoIterator<Item = &'a ForwardedElement>,
    {
        let mut it = input.into_iter();
        let mut forwarded = Forwarded::new(it.next()?.clone());
        forwarded.extend(it.cloned());
        Some(forwarded)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn assert_forward_header<T: ForwardHeader>() {}

    #[test]
    fn test_forward_header_impls() {
        assert_forward_header::<Forwarded>();
        assert_forward_header::<Via>();
        assert_forward_header::<XForwardedFor>();
        assert_forward_header::<XForwardedHost>();
        assert_forward_header::<XForwardedProto>();
        assert_forward_header::<CFConnectingIp>();
        assert_forward_header::<TrueClientIp>();
        assert_forward_header::<XClientIp>();
        assert_forward_header::<ClientIp>();
        assert_forward_header::<XRealIp>();
    }
}