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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
//! Path Filters
//!
//! The filters here work on the "path" of requests.
//!
//! - [`path`](./fn.path.html) matches a specific segment, like `/foo`.
//! - [`param`](./fn.param.html) tries to parse a segment into a type, like `/:u16`.
//! - [`index`](./fn.index.html) matches when the path end is found.
//! - [`path!`](../../macro.path.html) eases combining multiple `path` and `param` filters.
//!
//! # Routing
//!
//! Routing in warp is simple yet powerful.
//!
//! First up, matching a single segment:
//!
//! ```
//! use warp::Filter;
//!
//! // GET /hi
//! let hi = warp::path("hi").map(|| {
//!     "Hello, World!"
//! });
//! ```
//!
//! How about multiple segments? It's easiest with the `path!` macro:
//!
//! ```
//! # #[macro_use] extern crate warp; fn main() {
//! # use warp::Filter;
//! // GET /hello/from/warp
//! let hello_from_warp = path!("hello" / "from" / "warp").map(|| {
//!     "Hello from warp!"
//! });
//! # }
//! ```
//!
//! Neat! But do I handle **parameters** in paths?
//!
//! ```
//! # #[macro_use] extern crate warp; fn main() {
//! # use warp::Filter;
//! // GET /sum/:u32/:u32
//! let sum = path!("sum" / u32 / u32).map(|a, b| {
//!     format!("{} + {} = {}", a, b, a + b)
//! });
//! # }
//! ```
//!
//! In fact, any type that implements `FromStr` can be used, in any order:
//!
//! ```
//! # #[macro_use] extern crate warp; fn main() {
//! # use warp::Filter;
//! // GET /:u16/times/:u16
//! let times = path!(u16 / "times" / u16).map(|a, b| {
//!     format!("{} times {} = {}", a, b, a * b)
//! });
//! # }
//! ```
//!
//! Oh shoot, those math routes should be **mounted** at a different path,
//! is that possible? Yep!
//!
//! ```
//! # use warp::Filter;
//! # let sum = warp::any().map(warp::reply);
//! # let times = sum.clone();
//! // GET /math/sum/:u32/:u32
//! // GET /math/:u16/times/:u16
//! let math = warp::path("math");
//! let math_sum = math.and(sum);
//! let math_times = math.and(times);
//! ```
//!
//! What! `and`? What's that do?
//!
//! It combines the filters in a sort of "this and then that" order. In fact,
//! it's exactly what the `path!` macro has been doing internally.
//!
//! ```
//! # use warp::Filter;
//! // GET /bye/:string
//! let bye = warp::path("bye")
//!     .and(warp::path::param())
//!     .map(|name: String| {
//!         format!("Good bye, {}!", name)
//!     });
//! ```
//!
//! Ah, so, can filters do things besides `and`?
//!
//! Why, yes they can! They can also `or`! As you might expect, `or` creates a
//! "this or else that" chain of filters. If the first doesn't succeed, then
//! it tries the other.
//!
//! So, those `math` routes could have been **mounted** all as one, with `or`.
//!
//!
//! ```
//! # use warp::Filter;
//! # let sum = warp::any().map(warp::reply);
//! # let times = sum.clone();
//! // GET /math/sum/:u32/:u32
//! // GET /math/:u16/times/:u16
//! let math = warp::path("math")
//!     .and(sum.or(times));
//! ```
//!
//! It turns out, using `or` is how you combine everything together into a
//! single API.
//!
//! ```
//! # use warp::Filter;
//! # let hi = warp::any().map(warp::reply);
//! # let hello_from_warp = hi.clone();
//! # let bye = hi.clone();
//! # let math = hi.clone();
//! // GET /hi
//! // GET /hello/from/warp
//! // GET /bye/:string
//! // GET /math/sum/:u32/:u32
//! // GET /math/:u16/times/:u16
//! let routes = hi
//!     .or(hello_from_warp)
//!     .or(bye)
//!     .or(math);
//! ```

use std::fmt;
use std::str::FromStr;

use http::uri::PathAndQuery;

use ::filter::{Filter, filter_fn, Tuple, One, one};
use ::never::Never;
use ::reject::{self, Rejection};


/// Create an exact match path segment `Filter`.
///
/// This will try to match exactly to the current request path segment.
///
/// # Panics
///
/// Exact path filters cannot be empty, or contain slashes.
pub fn path(p: &'static str) -> impl Filter<Extract=(), Error=Rejection> + Copy {
    assert!(!p.is_empty(), "exact path segments should not be empty");
    assert!(!p.contains('/'), "exact path segments should not contain a slash: {:?}", p);

    segment(move |seg| {
        trace!("{:?}?: {:?}", p, seg);
        if seg == p {
            Ok(())
        } else {
            Err(reject::not_found())
        }
    })
}

/// Matches the end of a route.
pub fn index() -> impl Filter<Extract=(), Error=Rejection> + Copy {
    filter_fn(move |route| {
        if route.path().is_empty() {
            Ok(())
        } else {
            Err(reject::not_found())
        }
    })
}

/// Extract a parameter from a path segment.
///
/// This will try to parse a value from the current request path
/// segment, and if successful, the value is returned as the `Filter`'s
/// "extracted" value.
///
/// If the value could not be parsed, rejects with a `404 Not Found`.
///
/// # Example
///
/// ```
/// use warp::Filter;
///
/// let route = warp::path::param()
///     .map(|id: u32| {
///         format!("You asked for /{}", id)
///     });
/// ```
pub fn param<T: FromStr + Send>() -> impl Filter<Extract=One<T>, Error=Rejection> + Copy {
    segment(|seg| {
        trace!("param?: {:?}", seg);
        if seg.is_empty() {
            return Err(reject::not_found());
        }
        T::from_str(seg)
            .map(one)
            .map_err(|_| reject::not_found())
    })
}

/// Extract the unmatched tail of the path.
///
/// This will return a `Tail`, which allows access to the rest of the path
/// that previous filters have not already matched.
///
/// # Example
///
/// ```
/// use warp::Filter;
///
/// let route = warp::path("foo")
///     .and(warp::path::tail())
///     .map(|tail| {
///         // GET /foo/bar/baz would return "bar/baz".
///         format!("The tail after foo is {:?}", tail)
///     });
/// ```
pub fn tail() -> impl Filter<Extract=One<Tail>, Error=Never> + Copy {
    filter_fn(move |route| {
        let path = route
            .uri()
            .path_and_query()
            .expect("server URIs should always have path_and_query")
            .clone();
        let idx = route.matched_path_index();

        // Giving the user the full tail means we assume the full path
        // has been matched now.
        let end = path.path().len() - idx;
        route.set_unmatched_path(end);

        Ok(one(Tail {
            path,
            start_index: idx,
        }))
    })
}

/// Represents that tail part of a request path, returned by the `tail()` filter.
pub struct Tail {
    path: PathAndQuery,
    start_index: usize,
}

impl Tail {
    /// Get the `&str` representation of the remaining path.
    pub fn as_str(&self) -> &str {
        &self.path.path()[self.start_index..]
    }
}

impl fmt::Debug for Tail {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(self.as_str(), f)
    }
}

fn segment<F, U>(func: F) -> impl Filter<Extract=U, Error=Rejection> + Copy
where
    F: Fn(&str) -> Result<U, Rejection> + Copy,
    U: Tuple + Send,
{
    filter_fn(move |route| {
        let (u, idx) = {
            let seg = route.path()
                .splitn(2, '/')
                .next()
                .expect("split always has at least 1");
            (func(seg)?, seg.len())
        };
        route.set_unmatched_path(idx);
        Ok(u)
    })
}

/// Convenient way to chain multiple path filters together.
///
/// Any number of either type identifiers or string expressions can be passed,
/// each separated by a forward slash (`/`). Strings will be used to match
/// path segments exactly, and type identifiers are used just like
/// [`param`](filters::path::param) filters.
///
/// # Example
///
/// ```
/// # #[macro_use] extern crate warp; fn main() {
/// use warp::Filter;
///
/// // Match `/sum/:a/:b`
/// let route = path!("sum" / u32 / u32)
///     .map(|a, b| {
///         format!("{} + {} = {}", a, b, a + b)
///     });
/// # }
/// ```
///
/// The equivalent filter chain without using the `path!` macro looks this:
///
/// ```
/// use warp::Filter;
///
/// let route = warp::path("sum")
///     .and(warp::path::param::<u32>())
///     .and(warp::path::param::<u32>())
///     .map(|a, b| {
///         format!("{} + {} = {}", a, b, a + b)
///     });
/// ```
///
/// In fact, this is exactly what the macro expands to.
#[macro_export]
macro_rules! path {
    (@start $first:tt $(/ $tail:tt)*) => ({
        let __p = path!(@segment $first);
        $(
        let __p = $crate::Filter::and(__p, path!(@segment $tail));
        )*
        __p
    });
    (@segment $param:ty) => (
        $crate::path::param::<$param>()
    );
    (@segment $s:expr) => (
        $crate::path($s)
    );
    ($($pieces:tt)*) => (
        path!(@start $($pieces)*)
    );
}