These days realtime chat is a basic feature of any app. I also wanted to develop one for my app. I went through a lot of blogs and tutorials but most of them talked about creating a community chat system that anyone can join and start sending the messages. I wanted something in which I can create rooms as well. So here I’m sharing how I developed it.
Prerequisites
I’ve used gin just because I was already using it in my project and also it claims to feature a martini-like API with a performance that is up to 40 times faster.
Server
Create a file main.go that will initialise your server routes and WebSocket. For our simple application, we just want 2 routes:
/
— to show our chat web UI./ws
— to handle the WebSocket.
func main() {
go h.run()
router := gin.New()
router.LoadHTMLFiles("index.html")
router.GET("/room/:roomId", func(c *gin.Context) {
c.HTML(200, "index.html", nil)
})
router.GET("/ws/:roomId", func(c *gin.Context) {
roomId := c.Param("roomId")
serveWs(c.Writer, c.Request, roomId)
})…