Realtime Chat Rooms in Golang with WebSocket

Anup Kumar Panwar
5 min readApr 26, 2020

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

  1. https://github.com/gin-gonic/gin
  2. https://github.com/gorilla/websocket

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:

  1. / — to show our chat web UI.
  2. /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)
})

--

--

Anup Kumar Panwar
Anup Kumar Panwar

Written by Anup Kumar Panwar

Engineer @ Zepto | Ex-Gojek | Founder at The Algorithms | GSoC’18 @ FOSSASIA | And lots of Music & Football

Responses (3)