OnMessage: func(ctx context.Context, s *live.Session, topic string, data []byte) {
userID := s.Value().(string)
switch topic {
case "join_room":
var req struct{ Room string `json:"room"` }
json.Unmarshal(data, &req)
// Subscribe to room
server.Subscribe(s, "room:"+req.Room)
// Notify room
msg, _ := json.Marshal(map[string]string{"type": "join", "user": userID})
server.Publish("room:"+req.Room, msg)
case "leave_room":
var req struct{ Room string `json:"room"` }
json.Unmarshal(data, &req)
// Notify room
msg, _ := json.Marshal(map[string]string{"type": "leave", "user": userID})
server.Publish("room:"+req.Room, msg)
// Unsubscribe
server.Unsubscribe(s, "room:"+req.Room)
case "room_message":
var req struct {
Room string `json:"room"`
Text string `json:"text"`
}
json.Unmarshal(data, &req)
msg, _ := json.Marshal(map[string]string{
"type": "message",
"user": userID,
"text": req.Text,
})
server.Publish("room:"+req.Room, msg)
}
}