1 #![deny(warnings)]
2 
3 use std::convert::Infallible;
4 use std::str::FromStr;
5 use std::time::Duration;
6 use warp::Filter;
7 
8 #[tokio::main]
main()9 async fn main() {
10     // Match `/:Seconds`...
11     let routes = warp::path::param()
12         // and_then create a `Future` that will simply wait N seconds...
13         .and_then(sleepy);
14 
15     warp::serve(routes).run(([127, 0, 0, 1], 3030)).await;
16 }
17 
sleepy(Seconds(seconds): Seconds) -> Result<impl warp::Reply, Infallible>18 async fn sleepy(Seconds(seconds): Seconds) -> Result<impl warp::Reply, Infallible> {
19     tokio::time::delay_for(Duration::from_secs(seconds)).await;
20     Ok(format!("I waited {} seconds!", seconds))
21 }
22 
23 /// A newtype to enforce our maximum allowed seconds.
24 struct Seconds(u64);
25 
26 impl FromStr for Seconds {
27     type Err = ();
from_str(src: &str) -> Result<Self, Self::Err>28     fn from_str(src: &str) -> Result<Self, Self::Err> {
29         src.parse::<u64>().map_err(|_| ()).and_then(|num| {
30             if num <= 5 {
31                 Ok(Seconds(num))
32             } else {
33                 Err(())
34             }
35         })
36     }
37 }
38