Member-only story

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)
})
router.Run("0.0.0.0:8080")
}

The index.html is just a simple web client for our app where users can chat. We will talk about simple things later. There are 2 visible functions: go h.run() and serveWs().

I personally don’t like big files, so let’s end our main.go here only create another file called conn.go in the main package and keep our serveWs() function there.

func serveWs(w http.ResponseWriter, r *http.Request, roomId string) {
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err.Error())
return
}
c := &connection{send: make(chan []byte, 256), ws: ws}
s := subscription{c, roomId}
h.register <- s
go s.writePump()
go s.readPump()
}

Upgrader specifies parameters for upgrading an HTTP connection to a WebSocket connection. For upgrader has following configuration.

var upgrader = websocket.Upgrader{
ReadBufferSize: 1024…

--

--

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)

Write a response