From a719e780019116332e96bca79ce6869b9be8f66d Mon Sep 17 00:00:00 2001 From: Adam <24621027+adoyle0@users.noreply.github.com> Date: Tue, 16 Jul 2024 20:49:24 -0400 Subject: [PATCH] user struct --- src/api.rs | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/src/api.rs b/src/api.rs index c30b24f..c327c56 100644 --- a/src/api.rs +++ b/src/api.rs @@ -20,7 +20,12 @@ fn greeting(state: &Arc) -> String { ) } -pub async fn websocket(stream: WebSocket, state: Arc, who: SocketAddr) { +pub struct User { + name: String, + addr: SocketAddr, +} + +pub async fn websocket(stream: WebSocket, state: Arc, who: User) { // By splitting, we can send and receive at the same time. let (mut sender, mut receiver) = stream.split(); @@ -31,7 +36,7 @@ pub async fn websocket(stream: WebSocket, state: Arc, who: SocketAddr) let mut rx = state.tx.subscribe(); // ANNOUNCE THY PRESENCE - let msg = format!("{who} joined."); + let msg = format!("{} joined.", who.name); tracing::debug!("{msg}"); let _ = state.tx.send(msg); @@ -47,7 +52,7 @@ pub async fn websocket(stream: WebSocket, state: Arc, who: SocketAddr) // handle new incoming messages let mut recv_task = tokio::spawn(async move { while let Some(Ok(message)) = receiver.next().await { - message_handler(message, &state, who).await + message_handler(message, &state, who.addr).await } }); @@ -65,5 +70,14 @@ pub async fn websocket_handler( State(state): State>, ) -> impl IntoResponse { tracing::debug!("New connection from {addr}"); - ws.on_upgrade(move |socket| websocket(socket, state, addr)) + ws.on_upgrade(move |socket| { + websocket( + socket, + state, + User { + name: "Anonymous".to_string(), + addr, + }, + ) + }) }