1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
use maw::prelude::*;
#[tokio::main]
async fn main() -> Result<(), MawError> {
tracing_subscriber::fmt::init();
let app = App::new().router(
Router::new()
// Basic echo server
.ws("/ws", async |mut ws| {
while let Some(Ok(msg)) = ws.recv().await {
match msg {
WsMessage::Text(txt) => {
ws.send(format!("Echo: {txt}")).await.ok();
}
WsMessage::Binary(data) => {
ws.send(data).await.ok();
}
WsMessage::Close(_) => break,
_ => {}
}
}
})
// this ^ is equivalent to this v, use the latter if you need access to the request context
.get("/ws2", async |c: &mut Ctx| {
c.upgrade_websocket(async move |mut ws| {
while let Some(Ok(msg)) = ws.recv().await {
match msg {
WsMessage::Text(txt) => {
ws.send(format!("Echo: {txt}")).await.ok();
}
WsMessage::Binary(data) => {
ws.send(data).await.ok();
}
WsMessage::Close(_) => break,
_ => {}
}
}
})?;
Ok(())
}),
);
app.listen("127.0.0.1:3000").await
}