X-Git-Url: https://piware.de/gitweb/?a=blobdiff_plain;ds=sidebyside;f=warp-server%2Fsrc%2Fmain.rs;h=06977e62cf4e50911b5e00ba6f866c2daa49dc52;hb=24b1b69d58d85224cb8e5c8965b5a9cd545f0ffb;hp=70b3cc3f516dbf3bfb622a7f2231435682b0d609;hpb=660eb0d2c9664a89a379f0d65923a4c8721a20b8;p=learn-rust.git diff --git a/warp-server/src/main.rs b/warp-server/src/main.rs index 70b3cc3..06977e6 100644 --- a/warp-server/src/main.rs +++ b/warp-server/src/main.rs @@ -1,12 +1,41 @@ +use futures_util::{FutureExt, StreamExt}; use warp::Filter; +// GET /hello/warp => 200 OK with body "Hello, warp!" +async fn hello(name: String, agent: String) -> Result { + Ok(format!("Hello, {} from {}!", name, agent)) +} + +// websocat ws://127.0.0.1:3030/ws-echo +async fn ws_echo_connected(websocket: warp::ws::WebSocket) { + // echo all messages back + let (tx, rx) = websocket.split(); + rx.forward(tx).map(|result| { + if let Err(e) = result { + log::warn!("websocket error: {:?}", e); + } + }).await; +} + #[tokio::main] async fn main() { - // GET /hello/warp => 200 OK with body "Hello, warp!" + env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init(); + let hello = warp::path!("hello" / String) - .map(|name| format!("Hello, {}!", name)); + .and(warp::header::("user-agent")) + .and_then(hello); + + let ws_echo = warp::path("ws-echo") + .and(warp::ws()) + .map(|ws: warp::ws::Ws| { + ws.on_upgrade(|websocket| { ws_echo_connected(websocket) }) + }); + + let api = hello + .or(ws_echo) + .with(warp::log("warp-server")); - warp::serve(hello) + warp::serve(api) .run(([127, 0, 0, 1], 3030)) .await; }