Exploring WebSockets with Golang and Fiber

Rajat Nigam
Dev Genius
Published in
3 min readDec 29, 2023

WebSockets were created to build a bridge during the communication so that data can flow back and forth between client and server. This blog discusses the simplest way to practice a Golang code using the Fiber web framework for making a WebSocket server. The given code can be found in the main.go file of the fiber-web-socket repository.

Cadillacs and Dinosaurs. 90’s video games. Nostalgic !!

Understanding the Golang WebSocket Code

Let’s break down the key components of the Golang code:

Fiber Setup

app := fiber.New()

This code is written to start a new Fiber application, which is a high-speed and efficient web framework used in Golang.

Middleware for WebSocket Upgrade

app.Use("/ws", func(c *fiber.Ctx) error {
if websocket.IsWebSocketUpgrade(c) {
c.Locals("allowed", true)
return c.Next()
}
return fiber.ErrUpgradeRequired
})

This middleware checks if the incoming request is intended for a WebSocket upgrade. If true, it sets a local flag and allows the request to proceed.

WebSocket Route

app.Get("/ws/:id", websocket.New(func(c *websocket.Conn) {
// Handle WebSocket connection here
}))

The `/ws/:id` route is going to be used to handle WebSocket connections. The functions such as open, close, message, etc present the logic for various WebSocket operations to perform inside the WebSocket handler function.

WebSocket Operations

log.Println(c.Locals("allowed"))
log.Println(c.Params("id"))
log.Println(c.Query("v"))
log.Println(c.Cookies("session"))

These lines demonstrate how to access local variables, parameters, query parameters, and cookies from the WebSocket context.

if messageType, msg, err = c.ReadMessage(); err != nil {
log.Println("read error :", err)
break
}

The code reads incoming messages from the WebSocket connection.

if err = c.WriteMessage(messageType, []byte(fmt.Sprintf("Server: %s", response))); err != nil {
log.Println("Write error: ", err)
break
}

It writes a response back to the WebSocket client.

The advantages and usage of WebSockets

Benefits

Real-time Communication: Through WebSocket, the clients and servers can communicate in a way that both the client-end and server-end may send or receive messages at any time.

Reduced Latency: WebSockets provide low latency because it removes the need to establish a new connection every time.

Efficient Data Transfer: WebSockets protocols are more efficient as they have less overhead and it makes them favorable for applications that require high performance.

Use Cases

Chat Applications: WebSjsons are used to send instantaneous messages through chat applications.

Online Gaming: Games played by multiple users in real-time can be developed on WebSjson for better communication among the networks.

Financial Dashboards: WebSockets are the best option to get real-time financial data to provide the latest news for traders.

Advantages of Golang compared to Java and Python

Concurrency and Performance
Golang’s concurrency model is perfect for handling thousands of interactions at once; this model is built on top of goroutines and channels. Python and Java are not remarkably good at managing a whole lot of connections at the same time using their thread-based concurrency models.

Speed and Efficiency
The compiled language always has a faster speed than the interpretable language like Python. Also, Golang’s static typing facility can notify errors when compiling the code which ultimately increases the reliability of the code.

Simplicity and Readability
Go language focuses on writing a short, clear, and understandable syntax for writing the code. This makes it easy to maintain and clean the code base. The WebSocket servers are easily understood if a developer is new to the code which helps in the development.

Conclusion
In this blog post, we created a WebSocket server by implementing Golang code using the Fiber web framework. Use cases and benefits of web sockets were cleared. Also, it was discussed that Golang is much better than Python and Java for making scalable web socket applications.

For a better fast WebSocket server, and to communicate in real-time, Golang and fiber must be preferred. One can look into the fiber-web-socket repository to get a better understanding of the code and figure out how they can tweak it to fulfill their unique use cases.

Happy coding!

Sign up to discover human stories that deepen your understanding of the world.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Published in Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development

Written by Rajat Nigam

I'm a lifetime student of software engineering. Professionally I work in the capacity of Individual Contributor, Trainer, Lead Engineer and an Architect.

No responses yet

Write a response