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
//! Route object and DSL

use std::sync::Arc;

use http::StatusCode;

use crate::{route_recognizer::Router, Endpoint, EndpointExt, IntoResponse, Request, Response};

/// Routing object
#[derive(Default)]
pub struct Route {
    router: Router<Box<dyn Endpoint<Output = Response>>>,
}

impl Route {
    /// Add an [Endpoint] to the specified path.
    ///
    /// You can match the full path or wildcard path, and use the
    /// [`Path`](crate::web::Path) extractor to get the path parameters.
    ///
    /// # Example
    ///
    /// ```
    /// use poem::{handler, route, web::Path};
    ///
    /// #[handler]
    /// async fn a() {}
    ///
    /// #[handler]
    /// async fn b(Path((group, name)): Path<(String, String)>) {}
    ///
    /// #[handler]
    /// async fn c(Path(path): Path<String>) {}
    ///
    /// let app = route()
    ///     // full path
    ///     .at("/a/b", a)
    ///     // capture parameters
    ///     .at("/b/:group/:name", b)
    ///     // capture tail path
    ///     .at("/c/*path", c);
    /// ```
    pub fn at(mut self, path: &str, ep: impl Endpoint) -> Self {
        self.router.add(path, Box::new(ep.map_to_response()));
        self
    }

    /// Nest a `Endpoint` to the specified path.
    pub fn nest(mut self, path: &str, ep: impl Endpoint) -> Self {
        let ep = Arc::new(ep);
        let path = path.trim_end_matches('/');

        struct Nest<T>(T);

        #[async_trait::async_trait]
        impl<E: Endpoint> Endpoint for Nest<E> {
            type Output = Response;

            async fn call(&self, mut req: Request) -> Self::Output {
                let idx = req.state().match_params.0.len() - 1;
                let (name, value) = req.state_mut().match_params.0.remove(idx);
                assert_eq!(name, "--poem-rest");
                req.set_uri(
                    http::uri::Builder::new()
                        .path_and_query(value)
                        .build()
                        .unwrap(),
                );
                self.0.call(req).await.into_response()
            }
        }

        struct Root<T>(T);

        #[async_trait::async_trait]
        impl<E: Endpoint> Endpoint for Root<E> {
            type Output = Response;

            async fn call(&self, mut req: Request) -> Self::Output {
                req.set_uri(
                    http::uri::Builder::new()
                        .path_and_query("/")
                        .build()
                        .unwrap(),
                );
                self.0.call(req).await.into_response()
            }
        }

        assert!(
            path.find('*').is_none(),
            "wildcards are not allowed in the nest path."
        );
        self.router.add(
            &format!("{}/*--poem-rest", path),
            Box::new(Nest(ep.clone())),
        );
        self.router.add(path, Box::new(Root(ep)));
        self
    }
}

/// Create a new routing object.
pub fn route() -> Route {
    Route {
        router: Default::default(),
    }
}

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

    fn check(&self, req: &Request) -> bool {
        self.router.recognize(req.uri().path()).is_ok()
    }

    async fn call(&self, mut req: Request) -> Self::Output {
        let m = match self.router.recognize(req.uri().path()) {
            Ok(m) => m,
            Err(_) => return StatusCode::NOT_FOUND.into(),
        };

        if !m.handler.check(&req) {
            return StatusCode::NOT_FOUND.into();
        }

        req.state_mut().match_params.0.extend(m.params.0);
        m.handler.call(req).await
    }
}