» Go: Make Web Chat App with Socket.IO » 2. Development » 2.3 Chat Messages

Chat Messages

To the server side, one-on-one chat is basically to forward messages from one socket to another.

Update main.go:

@@ -9,6 +9,7 @@ import (
 )
 
 type User = map[string]interface{}
+type Data = User
 
 const port = 4000
 
@@ -43,6 +44,18 @@ func main() {
 			}
 			io.Sockets().Emit("contacts", items)
 		})
+
+		client.On("chat", func(args ...any) {
+			data, ok := args[0].(Data)
+			if !ok {
+				return
+			}
+			to, ok := data["to"].(string)
+			if !ok {
+				return
+			}
+			io.Sockets().To(socket.Room(to)).Emit("chat", data)
+		})
 	})
 
 	http.Handle("/socket.io/", io.ServeHandler(nil))

data has below fields:

  • to: destination socket ID of the incoming message.
  • from: socket ID of the sender.
  • msg: message content.

io.Sockets().To(...).Emit(...) allows you to target specific sockets or rooms when emitting events.

PrevNext