From 24b1b69d58d85224cb8e5c8965b5a9cd545f0ffb Mon Sep 17 00:00:00 2001 From: Martin Pitt Date: Sun, 6 Nov 2022 11:53:58 +0100 Subject: [PATCH] warp-server: Move handlers into proper functions This is easier to follow, and makes it more obvious what the types are. --- warp-server/src/main.rs | 34 ++++++++++++++++++++-------------- 1 file changed, 20 insertions(+), 14 deletions(-) diff --git a/warp-server/src/main.rs b/warp-server/src/main.rs index c8ecdf2..06977e6 100644 --- a/warp-server/src/main.rs +++ b/warp-server/src/main.rs @@ -1,32 +1,38 @@ 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() { env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init(); - // GET /hello/warp => 200 OK with body "Hello, warp!" let hello = warp::path!("hello" / String) .and(warp::header::("user-agent")) - .map(|name, agent| format!("Hello, {} from {}!", name, agent)); + .and_then(hello); - // websocat ws://127.0.0.1:3030/ws-echo - let echo = warp::path("ws-echo") + let ws_echo = warp::path("ws-echo") .and(warp::ws()) .map(|ws: warp::ws::Ws| { - ws.on_upgrade(|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); - } - }) - }) + ws.on_upgrade(|websocket| { ws_echo_connected(websocket) }) }); let api = hello - .or(echo) + .or(ws_echo) .with(warp::log("warp-server")); warp::serve(api) -- 2.39.5