Debian Codegraph @

third_party/rust/warp/examples/custom_methods.rs

raw
1 #![deny(warnings)]
2 use std::net::SocketAddr;
3
4 use warp::hyper::StatusCode;
5 use warp::{hyper::Method, reject, Filter, Rejection, Reply};
6
7 #[derive(Debug)]
8 struct MethodError;
9 impl reject::Reject for MethodError {}
10
11 const FOO_METHOD: &'static str = "FOO";
12 const BAR_METHOD: &'static str = "BAR";
13
14 fn method(name: &'static str) -> impl Filter<Extract = (), Error = Rejection> + Clone {
15 warp::method()
16 .and_then(move |m: Method| async move {
17 if m == name {
18 Ok(())
19 } else {
20 Err(reject::custom(MethodError))
21 }
22 })
23 .untuple_one()
24 }
25
26 pub async fn handle_not_found(reject: Rejection) -> Result<impl Reply, Rejection> {
27 if reject.is_not_found() {
28 Ok(StatusCode::NOT_FOUND)
29 } else {
30 Err(reject)
31 }
32 }
33
34 pub async fn handle_custom(reject: Rejection) -> Result<impl Reply, Rejection> {
35 if reject.find::<MethodError>().is_some() {
36 Ok(StatusCode::METHOD_NOT_ALLOWED)
37 } else {
38 Err(reject)
39 }
40 }
41
42 #[tokio::main]
43 async fn main() -> Result<(), Box<dyn std::error::Error>> {
44 let address: SocketAddr = "[::]:3030".parse()?;
45
46 let foo_route = method(FOO_METHOD)
47 .and(warp::path!("foo"))
48 .map(|| "Success")
49 .recover(handle_not_found);
50
51 let bar_route = method(BAR_METHOD)
52 .and(warp::path!("bar"))
53 .map(|| "Success")
54 .recover(handle_not_found);
55
56 warp::serve(foo_route.or(bar_route).recover(handle_custom))
57 .run(address)
58 .await;
59
60 Ok(())
61 }