2 use futures_util::{FutureExt, StreamExt, SinkExt};
4 // GET /hello/warp => 200 OK with body "Hello, warp!"
5 pub async fn hello(name: String, agent: String) -> Result<impl warp::Reply, warp::Rejection> {
6 Ok(format!("Hello, {} from {}!", name, agent))
9 // websocat ws://127.0.0.1:3030/ws-echo
10 pub 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);
20 // websocat ws://127.0.0.1:3030/ws-rev
21 pub async fn ws_rev_connected(websocket: warp::ws::WebSocket) {
22 // echo all messages back
23 tokio::task::spawn(async {
24 let (mut tx, mut rx) = websocket.split();
25 while let Some(message) = rx.next().await {
26 let msg = match message {
29 log::error!("websocket error: {}", e);
33 log::info!("ws_rev_connected: got message: {:?}", msg);
39 let text = msg.to_str().unwrap();
40 let rev = text.chars().rev().collect::<String>();
41 if let Err(e) = tx.send(warp::ws::Message::text(rev)).await {
43 log::info!("peer disconnected: {}", e);
48 let mut rev = msg.into_bytes();
50 if let Err(e) = tx.send(warp::ws::Message::binary(rev)).await {
52 log::info!("peer disconnected: {}", e);
57 log::info!("ws_rev_connected ended");
66 pub fn hello() -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone {
67 warp::path!("hello" / String)
68 .and(warp::header::<String>("user-agent"))
69 .and_then(handlers::hello)
72 pub fn ws_echo() -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone {
75 .map(|ws: warp::ws::Ws| { ws.on_upgrade(handlers::ws_echo_connected) })
78 pub fn ws_rev() -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone {
81 .map(|ws: warp::ws::Ws| { ws.on_upgrade(handlers::ws_rev_connected) })
84 pub fn api() -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone {
88 .with(warp::log("warp-server"))
94 env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
95 warp::serve(filters::api())
96 .run(([127, 0, 0, 1], 3030))