一 代码结构图
二 message 包
chatroom\common\message\message.go
package message
// 定义各种消息类型
const (
LoginMesType = "LoginMes"
LoginResMesType = "LoginResMes"
RegisterMesType = "RegisterMes"
RegisterResMesType = "RegisterResMes"
NotifyUserStatusMesType = "NotifyUserStatusMes"
SmsMesType = "SmsMes"
)
// 定义各种用户状态
const (
UserOnline = iota
UserOffline
UserBusyStatus
)
// 消息包括消息类型和消息数据
type Message struct {
Type string `json:"type"` // 消息类型
Data string `json:"data"` // 消息数据
}
// 登录消息
type LoginMes struct {
UserId int `json:"userId"` // 用户id
UserPwd string `json:"userPwd"` // 用户密码
UserName string `json:"userName"` // 用户名
}
// 登录响应消息
type LoginResMes struct {
Code int `json:"code"` // 返回状态码:500-表示该用户未注册 200-表示登录成功
UsersId []int // 用户 id 切片
Error string `json:"error"` // 错误信息
}
// 注册消息
type RegisterMes struct {
User User `json:"user"` // 类型就是 User 结构体.
}
// 注册响应消息
type RegisterResMes struct {
Code int `json:"code"` // 返回状态码 400 表示该用户已经占有 200表示注册成功
Error string `json:"error"` // 返回错误信息
}
// 服务器端推送用户状态变化的消息
type NotifyUserStatusMes struct {
UserId int `json:"userId"` // 用户id
Status int `json:"status"` // 用户的状态
}
// 群聊消息
type SmsMes struct {
Content string `json:"content"` // 消息内容
User // 使用匿名结构体,继承 User
}
chatroom\common\message\user.go
package message
// 用户结构体
type User struct {
// 为了序列化和反序列化成功,必须保证用户信息的 json 字符串的 key 和 结构体的字段对应的 tag 名字一致
UserId int `json:"userId"`
UserPwd string `json:"userPwd"`
UserName string `json:"userName"`
UserStatus int `json:"userStatus"` // 用户状态
Sex string `json:"sex"` // 性别
}