Skip to content
a go websocket room manager for gin
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
README.md
client.go
msg.go
room-manager.go
room.go

README.md

Websocket room manager

Install:

$ go get github.com/kjda/wsm

Create a room manager:

package yourpackage

import (
	"github.com/kjda/wsm"
	"...."
)

type ChatRoom struct {
	*wsm.Room
	chatService *chat.serviceInterface
	Foo         string
}

func NewChatRoom(roomRoute string, chatService *chat.serviceInterface) *ChatRoom {
	// Create the room
	room := ChatRoom{
		wsm.NewRoom(roomRoute),
		chatService,
		"bar",
	}

	// setup room callbacks
	room.SetOnEnter(room.onEnter)
	room.SetOnLeave(room.onLeave)

	// add room message handlers
	room.AddHandler("chat", room.receiveChat)
	return &room
}

func (r *ChatRoom) onEnter(c *wsm.Client) {
	c.Send("welcome")
	countMsg := NewMsg("clients_count", &wsm.MsgPayload{
		"clients": r.Room.ClientsCount(),
	})
	c.SendMsg(countMsg)
	c.Room.Broadcast("enter", wsm.MsgPayload{
		"user": getUser(c.Context),
	})
}

func (r *ChatRoom) onLeave(c *wsm.Client) {
	c.Room.Broadcast("leave", &wsm.MsgPayload{
		"user": getUser(c.Context),
	})
}

func (r *ChatRoom) receiveChat(a *wsm.Action) {
	chat, ok := a.Msg.GetString("chat")
	if !ok {
		return
	}
	r.chatService.postChat(chat)
	r.Broadcast("new-chat", &wsm.MsgPayload{
		"user": getUser(a.Context),
		"chat": chat,
	})
}

func getUser(ctx *gin.Context) (user *models.User) {
	if userRaw, exists := ctx.Get("user"); exists {
		switch u := userRaw.(type) {
		case *models.User:
			user = u
		}
	}
	return user
}

create other rooms as needed:

type FooRoom struct {
  *wsm.Room
  Bar string
}

func NewFooRoom(roomRoute string, bar String) *FooRoom {
  //.. setup room
  return room
}
// ... etc

Add routing:

	import "github.com/kjda/wsm"

	r := gin.Default()
	wsock := r.Group("/ws")
	// wsock.Use(middleware.HeadersCors())
	// wsock.Use(middleware.Session())
	// wsock.Use(middleware.SessionSetUser(env.DB))
	{

		manager := wsm.NewRoomManager()

		//setup rooms
		chatRoom := NewChatRoom(chatService)
		chatRoom.Route = "chat-route"
		manager.AddRoom(chatRoom.Room)
		// will be accessible at: /ws/chat-route

		fooRoom := NewFooRoom("bar")
		chatRoom.Route = "foo"
		manager.AddRoom(fooRoom.Room)
		// will be accessible at: /ws/foo


		// setup routes
		wsock.GET("/:room", func(c *gin.Context) {
			roomName := c.Params.ByName("room")
			manager.HandleConnection(c, roomName)
		})
	}
You can’t perform that action at this time.