59 lines
1.9 KiB
Go
59 lines
1.9 KiB
Go
package models
|
||
|
||
import (
|
||
"time"
|
||
)
|
||
|
||
// Message 核心变更:增加 Room 字段,移除歧义字段
|
||
type Message struct {
|
||
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 时有效)
|
||
}
|
||
|
||
// 消息类型常量
|
||
const (
|
||
MsgTypeLogin = "login" // 服务端生成:用户上线事件
|
||
MsgTypeLogout = "logout" // 服务端生成:用户下线事件
|
||
MsgTypeBroadcast = "broadcast" // 全体用户广播(无视房间)
|
||
MsgTypeRoom = "room" // 房间消息(必须带 Room 字段)
|
||
MsgTypePrivate = "private" // 私聊(必须带 To 字段)
|
||
MsgTypeSystem = "system" // 服务端生成:系统通知
|
||
MsgTypeError = "error" // 服务端生成:定向错误提示
|
||
)
|
||
|
||
// 发送广播消息
|
||
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),
|
||
}
|
||
}
|