Creating Chatting Server with Websocket in Go

Photo by Volodymyr Hryshchenko on Unsplash

Library needed

Before we go right into programming, that’s one library that we need:

go get github.com/gorilla/websocket

The project structure

You like it simple, right?

  1. Websocket connection handler. We call it the Hub. It is a goroutine that save and remove the data of connected client and handle the message broadcast event
  2. Websocket client manager. It handle the Read and Write of Websocket of each client. Ideally, we create one goroutine for each. And 2 separate go routine for the reader and writer. (Total 3 goroutine for 1 client)

Test the Websocket Connection

Run the code

go run main.go
wscat -c http://127.0.0.1:8080/ws
wscat -c http://127.0.0.1:8080/ws

More improvement

There are plenty of room to be improve. Since I get the example from the repository itself. I also drop some “fancy” function and make it as minimal as I can. I drop the Ping/pong mechanism, queue messages and some message encodings. But, after we understand how it works, I think it can be your challenge to implement those by your self and add more advance features like custom ID, adding room features like Socket IO or anything that fit it to your needs.

*Molly Ringwald dancing in The Breakfast Club scene

I prefer old-school song and technology, as they are obvious and more understandable.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store