]> piware.de Git - learn-rust.git/blob - warp-server/src/main.rs
06977e62cf4e50911b5e00ba6f866c2daa49dc52
[learn-rust.git] / warp-server / src / main.rs
1 use futures_util::{FutureExt, StreamExt};
2 use warp::Filter;
3
4 // GET /hello/warp => 200 OK with body "Hello, warp!"
5 async fn hello(name: String, agent: String) -> Result<impl warp::Reply, warp::Rejection> {
6     Ok(format!("Hello, {} from {}!", name, agent))
7 }
8
9 // websocat ws://127.0.0.1:3030/ws-echo
10 async fn ws_echo_connected(websocket: warp::ws::WebSocket) {
11     // echo all messages back
12     let (tx, rx) = websocket.split();
13     rx.forward(tx).map(|result| {
14         if let Err(e) = result {
15             log::warn!("websocket error: {:?}", e);
16         }
17     }).await;
18 }
19
20 #[tokio::main]
21 async fn main() {
22     env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
23
24     let hello = warp::path!("hello" / String)
25         .and(warp::header::<String>("user-agent"))
26         .and_then(hello);
27
28     let ws_echo = warp::path("ws-echo")
29         .and(warp::ws())
30         .map(|ws: warp::ws::Ws| {
31             ws.on_upgrade(|websocket| { ws_echo_connected(websocket) })
32         });
33
34     let api = hello
35         .or(ws_echo)
36         .with(warp::log("warp-server"));
37
38     warp::serve(api)
39         .run(([127, 0, 0, 1], 3030))
40         .await;
41 }