Implementing WebSocket in Go

Enhancing Real-Time Communication in a Go Applications using WebSocket

Auriga Aristo
Indonesian Developer
5 min readMar 20, 2024

--

Simple WebSocket Illustration

Have you ever created an application with chat features, either in a web application or mobile application? You might use a Real-time Database in Firebase if you have developed a simple one. But have you ever considered making your real-time connection without any third party? This real-time connection is named WebSocket.

What is WebSocket?

Imagine you are at a party (the internet), and you have a walkie-talkie (HTTP) to talk with your friend on the other side of the room (the server). Whenever you want to say something, you must press the button (make a request), talk your message, and let go of the button, ending the conversation. Then, when your friend wants to reply, they do the same thing. It is working, but inconvenient.

Let’s switch the walkie-talkie to a phone call (WebSocket). You can call once until the party ends. You can talk (send data), listen (receive data), and even speak with each other at the same time (full-duplex). You don’t have to reconnect your connection whenever you have something to say. It’s like you have an open connection with each other effortlessly.

WebSocket is a technology that creates communication between one user and another. Using a WebSocket, you can send a message to a server and receive responses within one open connection. It is like having a continuous two-way connection between the user and the server.

How does it work?

WebSocket Process.
  • Opening the Connection
    It all starts with opening the connection, or usually, we call it a handshake. It is not the regular handshake; it is a special HTTP Request that upgrades from the basic HTTP to WebSocket.
  • Full-Duplex Connection
    Once the handshake is successful, the connection is established. This new connection is full-duplex, meaning data can flow in both directions simultaneously. It is identical to phone calls, where you can speak and listen simultaneously.
  • Data Transfer
    When using WebSocket, every user has a transmitter and a receiver, so every data can be sent within low latency without waiting for the reply or someone to close the connection. This connection is more efficient than the regular HTTP request because we don’t have to open and shut the connection for each request and response cycle.
  • Keeping the connection open
    The WebSocket connection will stay open, allowing real-time exchange until the user or the server decides to close it. This process is excellent for applications that require real-time updates, like real-time updates, chat applications and more.
  • Closing the connection
    Either the user or the server can initiate to close the connection. Once any user decides to close the connection, the party will send a request to close the connection so each party will close the connection.

Implementation

First, you need the WebSocket module added to the project. You can add this:

go get -u github.com/gorilla/websocket

Because I am using GoFiber, you can implement using this module:

go get github.com/gofiber/websocket/v2

Start by setting up the simple app. This code is our foundation.

To handle WebSocket connections, we need to add a middleware to tell the user that the route can be upgraded to a WebSocket connection. We use route /test as our WebSocket connection for this case.

Then, we need a handler to process the data it receives or sends. The function websocket.New will handle it. In the example below, the server prints every message that it gets and sends back with the same message.

Finally, call the setupRoutes in your main function and start the app.

Testing

To test the WebSocket connection, you may use Postman or else. As a simple choice, I’ll use a Firefox extension named “WebSocket Weasel.”

When you open the extension, you will find the following:

WebSocket Weasel Page

We must first input our URL, ws://localhost:3000/test, as our WebSocket connection to test the connection. Then, press open to open the WebSocket connection. When the connection has been established, the log will tell you that the connection is ready.

WebSocket Weasel Log

Afterward, you can type anything on the message console and press send. For every message you send, the server will send the message back to the console.

WebSocket Weasel Example Message Log

The message in orange is the message that you sent from the console.
The message in blue color is the message that the console received.

Whenever, you want to close the connection, you can press the close button.

Conclusion

Creating your WebSocket gives you flexibility for sending and receiving data and gives you complete control over the communication logic. WebSocket is efficient, especially for high-frequency data exchange, because it can skip the open-close connection multiple times and keep it open.

While it has many advantages, implementing WebSocket from scratch requires much effort and knowledge about handling the connection. This method requires you to manage the scalability, which can become more challenging as the user grows.

WebSocket will give you low-level control and flexibility but requires more effort to implement it. Firebase Real-time Database can be your better solution if you need something more straightforward to implement with automatic scalability.

When it comes to picking the right tool for your projects, it’s all about figuring out what you need. So, let’s dive in and explore your options!

--

--

Auriga Aristo
Indonesian Developer

4+ years in Backend Developer | PHP, Java/Kotlin, MySQL, Golang | New story every week