]> piware.de Git - learn-rust.git/blobdiff - warp-server/src/main.rs
warp-server: Add logging
[learn-rust.git] / warp-server / src / main.rs
index 70b3cc3f516dbf3bfb622a7f2231435682b0d609..1c75e734d32aca6e9552489815a19eb31d537e59 100644 (file)
@@ -1,12 +1,35 @@
+use futures_util::{FutureExt, StreamExt};
 use warp::Filter;
 
 #[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)
-        .map(|name| format!("Hello, {}!", name));
+        .and(warp::header::<String>("user-agent"))
+        .map(|name, agent| format!("Hello, {} from {}!", name, agent));
+
+    // websocat ws://127.0.0.1:3030/ws-echo
+    let 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 {
+                        eprintln!("websocket error: {:?}", e);
+                    }
+                })
+            })
+        });
+
+    let api = hello
+        .or(echo)
+        .with(warp::log("warp-server"));
 
-    warp::serve(hello)
+    warp::serve(api)
         .run(([127, 0, 0, 1], 3030))
         .await;
 }