WebSocket in Go: Building Real-Time Applications with Golang

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

WebSocket in Go: Building Real-Time Applications with Golang



Modern web applications increasingly require instant data transfer between client and server. Traditional HTTP request-response is not suitable for chats, online games, trading platforms, and real-time monitoring. The WebSocket protocol comes to the rescue, establishing a persistent bidirectional connection. In this article on pythonlib.ru, we will explore how to build a real-time application in Go (Golang) using WebSocket.



Go is ideal for this task thanks to its built-in support for concurrency (goroutines and channels) and high performance. Together, we will write a simple WebSocket server, implement a chat, and look at typical problems.



What is WebSocket and why is it needed in Go?



WebSocket is a protocol that works over TCP. It is initiated as an HTTP request (handshake), after which the connection is "upgraded" to a persistent bidirectional channel. Unlike long polling or Server-Sent Events, WebSocket allows the server and client to send data at any time without re-establishing the connection.



Advantages of using WebSocket in Go:



  • Concurrency: goroutines easily handle thousands of simultaneous connections.
  • Performance: minimal memory consumption per connection.
  • Simplicity: the standard net/http library and the gorilla/websocket package make the code concise.


WebSocket is often used in:

  • Chat systems and messengers
  • Online editors (Google Docs)
  • Trading terminals (stock quotes)
  • Games and simulators


Installing and configuring WebSocket in Go



Go does not have built-in WebSocket support in the standard library, but there is an excellent package gorilla/websocket. Let's install it:



go get github.com/gorilla/websocket


Let's create a minimal HTTP server that will handle WebSocket connections. First, we'll write a handler function that "upgrades" the HTTP request to WebSocket.



package main

import ( "log" "net/http" "github.com/gorilla/websocket")

var upgrader = websocket.Upgrader{ CheckOrigin: func(r *http.Request) bool { return true // allow all origins (for development) },}

func handleWebSocket(w http.ResponseWriter, r *http.Request) { conn, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Print("Upgrade error:", err) return } defer conn.Close()

// Infinite loop for reading messages for { messageType, message, err := conn.ReadMessage() if err != nil { log.Println("Read error:", err) break } log.Printf("Received: %s", message)

// Echo response: send the same message back if err := conn.WriteMessage(messageType, message); err != nil { log.Println("Write error:", err) break } }}

func main() { http.HandleFunc("/ws", handleWebSocket) log.Println("Server started on :8080") log.Fatal(http.ListenAndServe(":8080", nil))}


This code creates a simple echo server. The client connects to ws://localhost:8080/ws and receives all sent messages back.



Creating a real-time chat in Go with WebSocket



Now let's make it more complex: we'll create a chat where all connected clients can see each other's messages. For this, we need to manage the list of connections and broadcast messages.



Main components:

  • Hub — a central manager that registers/removes clients and broadcasts messages.
  • Client — represents a single WebSocket connection.

Blogs

Book Recommendations