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
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
use crate::{
    endpoint::BoxEndpoint,
    http::{header, StatusCode},
    route::internal::trie::Trie,
    Endpoint, EndpointExt, IntoEndpoint, Request, Response,
};

/// Routing object for `HOST` header
#[derive(Default)]
pub struct RouteDomain {
    tree: Trie<BoxEndpoint<'static, Response>>,
}

impl RouteDomain {
    /// Create a `RouteDomain` object.
    pub fn new() -> Self {
        Default::default()
    }

    /// Add an [Endpoint] to the specified domain pattern.
    ///
    /// # Example
    ///
    /// ```
    /// use poem::{endpoint::make_sync, handler, http::header, Endpoint, Request, RouteDomain};
    ///
    /// let app = RouteDomain::new()
    ///     .add("example.com", make_sync(|_| "1"))
    ///     .add("www.+.com", make_sync(|_| "2"))
    ///     .add("*.example.com", make_sync(|_| "3"))
    ///     .add("*", make_sync(|_| "4"));
    ///
    /// fn make_request(host: &str) -> Request {
    ///     Request::builder().header(header::HOST, host).finish()
    /// }
    ///
    /// async fn do_request(app: &RouteDomain, req: Request) -> String {
    ///     app.call(req).await.into_body().into_string().await.unwrap()
    /// }
    ///
    /// # tokio::runtime::Runtime::new().unwrap().block_on(async {
    /// assert_eq!(do_request(&app, make_request("example.com")).await, "1");
    /// assert_eq!(do_request(&app, make_request("www.abc.com")).await, "2");
    /// assert_eq!(do_request(&app, make_request("a.b.example.com")).await, "3");
    /// assert_eq!(do_request(&app, make_request("rust-lang.org")).await, "4");
    /// assert_eq!(do_request(&app, Request::default()).await, "4");
    /// # });
    /// ```
    pub fn add<E>(mut self, pattern: impl AsRef<str>, ep: E) -> Self
    where
        E: IntoEndpoint,
        E::Endpoint: 'static,
    {
        self.tree.add(
            pattern.as_ref(),
            Box::new(ep.into_endpoint().map_to_response()),
        );
        self
    }
}

#[async_trait::async_trait]
impl Endpoint for RouteDomain {
    type Output = Response;

    async fn call(&self, req: Request) -> Self::Output {
        let host = req
            .headers()
            .get(header::HOST)
            .and_then(|host| host.to_str().ok())
            .unwrap_or_default();
        match self.tree.matches(host) {
            Some(ep) => ep.call(req).await,
            None => StatusCode::NOT_FOUND.into(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{endpoint::make_sync, handler, http::HeaderMap};

    async fn check(r: &RouteDomain, host: &str, value: &str) {
        let mut req = Request::builder();
        if !host.is_empty() {
            req = req.header(header::HOST, host);
        }
        assert_eq!(
            r.call(req.finish())
                .await
                .into_body()
                .into_string()
                .await
                .unwrap(),
            value
        );
    }

    #[tokio::test]
    async fn route_domain() {
        #[handler(internal)]
        fn h(headers: &HeaderMap) -> String {
            headers
                .get(header::HOST)
                .and_then(|value| value.to_str().ok())
                .unwrap_or_default()
                .to_string()
        }

        let r = RouteDomain::new()
            .add("example.com", make_sync(|_| "1"))
            .add("www.example.com", make_sync(|_| "2"))
            .add("www.+.com", make_sync(|_| "3"))
            .add("*.com", make_sync(|_| "4"))
            .add("*", make_sync(|_| "5"));

        check(&r, "example.com", "1").await;
        check(&r, "www.example.com", "2").await;
        check(&r, "www.abc.com", "3").await;
        check(&r, "abc.com", "4").await;
        check(&r, "rust-lang.org", "5").await;
        check(&r, "", "5").await;
    }

    #[tokio::test]
    async fn not_found() {
        let r = RouteDomain::new()
            .add("example.com", make_sync(|_| "1"))
            .add("www.example.com", make_sync(|_| "2"))
            .add("www.+.com", make_sync(|_| "3"))
            .add("*.com", make_sync(|_| "4"));

        assert_eq!(
            r.call(
                Request::builder()
                    .header(header::HOST, "rust-lang.org")
                    .finish()
            )
            .await
            .status(),
            StatusCode::NOT_FOUND,
        );
        assert_eq!(
            r.call(Request::default()).await.status(),
            StatusCode::NOT_FOUND,
        );
    }
}