WEBSOCKET
Create your first WebSocket service
Mihalis Tsoukalos explains how to use the Go programming language to work with the WebSocket protocol.
OUR EXPERT
Mihalis Tsoukalos is a systems engineer and a technical writer. He is the author of Go Systems Programming and Mastering Go. You can reach him at @mactsouk.
This tutorial covers the WebSocket protocol and how to work with it using the Go programming language. We’re going to develop a WebSocket client and a WebSocket server that can interact with each other. In the process, we are also going to learn the basics of Unix signal handling in Go and how to test a WebSocket server using the Websocat command line utility as well as JavaScript.
Go is an open source programming language and WebSocket is an open protocol. The same applies to HTML and JavaScript, as well as Linux. People make a living from open source projects, tools, technologies and ideas, so please recognise that and contribute in any way you can. Many thanks to all these people!
Gorilla sockets
To develop a small yet fully functional WebSocket server, we’re using the gorilla/websocket (https:// github.com/gorilla/websocket) module. The server implements the Echo service, which means that it automatically returns its input to the client. It also expects to get client input before sending data back.
Apart from gorilla/websocket, the golang.org/x/ net/websocket package offers another way of developing WebSocket clients and servers. However, according to its documentation, golang.org/x/net/websocket lacks some features and it is advised that you use https://godoc.org/github.com/gorilla/ websocket, the one used here, or https://godoc.org/nhooyr.io/websocket instead.
Here you can see the implementation of the wsHandler() function as well as the definition of the upgrader Go structure and the implementation of the rootHandler() handler function.
As gorilla/websocket is an external Go package and that by default all recent Go versions use modules, all source code should be put under ~/go/src to be compiled and executed using Go modules. If you have a Go project that uses gorilla/websocket and you want to download gorilla/websocket for the first time, you should execute go mod init and go mod tidy on each Go project directory that uses gorilla/websocket and Go takes care of the rest. Bear in mind that both commands should be executed only once to enable Go modules. If you want to start the process from scratch, you can delete go.mod and go.sum at any time and recreate them.