]> piware.de Git - learn-rust.git/blob - warp-server/src/main.rs
warp-server: Add echo websocket route
[learn-rust.git] / warp-server / src / main.rs
1 use futures_util::{FutureExt, StreamExt};
2 use warp::Filter;
3
4 #[tokio::main]
5 async fn main() {
6     // GET /hello/warp => 200 OK with body "Hello, warp!"
7     let hello = warp::path!("hello" / String)
8         .and(warp::header::<String>("user-agent"))
9         .map(|name, agent| format!("Hello, {} from {}!", name, agent));
10
11     // websocat ws://127.0.0.1:3030/ws-echo
12     let echo = warp::path("ws-echo")
13         .and(warp::ws())
14         .map(|ws: warp::ws::Ws| {
15             ws.on_upgrade(|websocket| {
16                 // echo all messages back
17                 let (tx, rx) = websocket.split();
18                 rx.forward(tx).map(|result| {
19                     if let Err(e) = result {
20                         eprintln!("websocket error: {:?}", e);
21                     }
22                 })
23             })
24         });
25
26     warp::serve(hello.or(echo))
27         .run(([127, 0, 0, 1], 3030))
28         .await;
29 }