在上一篇《Golang实战-一个聊天室的实现》中,我们按照书上写了个简单的聊天室,今天我们来加点我们自己的东西:
可新增房间,并切换房间。
要想新建房间,得有个房间的对象,保存房间的一些基本信息:
type RoomInfo struct {
Name string `json:"name"`
//删除房间时用,只有房间创建者可删除
CreaterId string `json:"creater_id"`
}
房间有了,下面是房间里的人:
type ClientInfo struct {
Id string `json:"id"`
Nickname string `json:"nickname"`
CurrentRoom RoomInfo `json:"current_room"`
ClientResource chan<- string
}
房间和人的关系应该是一对多的关系:
type Clients []*ClientInfo
type ChatRoom struct {
RoomMap map[RoomInfo]Clients
}
房间和人都定义好了,我们需要对房间有一些基本的增、删操作,将它们独立到一个文件db.go里:
package chat
type ClientInfo struct {
Id string `json:"id"`
Nickname string `json:"nickname"`
CurrentRoom RoomInfo `json:"current_room"`
ClientResource chan<- string
}
type RoomInfo struct {
Name string `json:"name"`
//删除房间时用,只有房间创建者可删除
CreaterId string `json:"creater_id"`
}
type Clients []*ClientInfo
type RoomList []RoomInfo
type ChatRoom struct {
RoomMap map[RoomInfo]Clients
}
func NewChatRoom() *ChatRoom {
return &ChatRoom{
RoomMap: make(map[RoomInfo]Clients),
}
}
func (c *ChatRoom) AddRoom(r RoomInfo) {
//判断房间是否已存在
_, ok := c.RoomMap[r]
if !ok {
c.RoomMap[r] = Clients{}
}
}
func (c *ChatRoom) AddClient(r RoomInfo, cli *ClientInfo) {
clients := c.RoomMap[r]
found := false
//防止重复添加
for _, client := range clients {
if client.Id == cli.Id {
found = true
}
}
if found == false {
cli.CurrentRoom = r
c.RoomMap[r] = append(clients, cli)
}
}
func (c *ChatRoom) RemoveClient(r RoomInfo, id string) (bool, int) {
clients, ok :=