2026-02-03 23:45:27 +08:00
|
|
|
|
package models
|
|
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
|
"time"
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
// Message 核心变更:增加 Room 字段,移除歧义字段
|
|
|
|
|
|
type Message struct {
|
2026-02-04 13:06:11 +08:00
|
|
|
|
Type string `json:"type"` // 消息类型(严格按常量)
|
|
|
|
|
|
User string `json:"user"` // 发送者(客户端填,服务端可校验)
|
|
|
|
|
|
Content string `json:"content"` // 消息内容
|
|
|
|
|
|
Time string `json:"time"` // 服务端统一覆盖为 RFC3339(防客户端篡改)
|
|
|
|
|
|
To string `json:"to,omitempty"` // 私聊目标(仅 type=private 时有效)
|
|
|
|
|
|
Room string `json:"room,omitempty"` // 房间ID(仅 type=room 时有效)
|
|
|
|
|
|
Count int64 `json:"count,omitempty"` // 在线人数(仅 type=user_count 时有效)
|
2026-02-03 23:45:27 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// 消息类型常量
|
|
|
|
|
|
const (
|
2026-02-04 13:06:11 +08:00
|
|
|
|
MsgTypeLogin = "login" // 服务端生成:用户上线事件
|
|
|
|
|
|
MsgTypeLogout = "logout" // 服务端生成:用户下线事件
|
|
|
|
|
|
MsgTypeBroadcast = "broadcast" // 全体用户广播(无视房间)
|
|
|
|
|
|
MsgTypeRoom = "room" // 房间消息(必须带 Room 字段)
|
|
|
|
|
|
MsgTypePrivate = "private" // 私聊(必须带 To 字段)
|
|
|
|
|
|
MsgTypeSystem = "system" // 服务端生成:系统通知
|
|
|
|
|
|
MsgTypeError = "error" // 服务端生成:定向错误提示
|
|
|
|
|
|
MsgTypeUserCount = "user_count" // 服务端生成:在线人数更新
|
2026-02-03 23:45:27 +08:00
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
// 发送广播消息
|
|
|
|
|
|
func SendBroadcastMessage(user, content string) *Message {
|
|
|
|
|
|
return &Message{
|
|
|
|
|
|
Type: MsgTypeBroadcast,
|
|
|
|
|
|
User: user,
|
|
|
|
|
|
Content: content,
|
|
|
|
|
|
Time: time.Now().UTC().Format(time.RFC3339),
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// 发送房间消息
|
|
|
|
|
|
func SendRoomMessage(user, roomID, content string) *Message {
|
|
|
|
|
|
return &Message{
|
|
|
|
|
|
Type: MsgTypeRoom,
|
|
|
|
|
|
User: user,
|
|
|
|
|
|
Room: roomID, // 显式绑定房间
|
|
|
|
|
|
Content: content,
|
|
|
|
|
|
Time: time.Now().UTC().Format(time.RFC3339),
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// 发送私聊消息
|
|
|
|
|
|
func SendPrivateMessage(sender, recipient, content string) *Message {
|
|
|
|
|
|
return &Message{
|
|
|
|
|
|
Type: MsgTypePrivate,
|
|
|
|
|
|
User: sender,
|
|
|
|
|
|
To: recipient, // 显式指定接收者
|
|
|
|
|
|
Content: content,
|
|
|
|
|
|
Time: time.Now().UTC().Format(time.RFC3339),
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|