Gorilla WebSocket library for Go (Golang) — Complete Guide

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

Gorilla WebSocket library for Go (Golang)



Gorilla WebSocket is one of the most popular and stable libraries for working with the WebSocket protocol in the Go language (Golang). It is part of the Gorilla Toolkit ecosystem and provides developers with a powerful, flexible, and high-performance tool for creating real-time applications: chats, real-time notifications, online games, monitoring dashboards, and much more.



The library fully implements the RFC 6455 specification, supports both server and client sides, and automatically handles message fragmentation, ping/pong mechanisms, and connection control. Gorilla WebSocket is written in pure Go with no external dependencies, making it lightweight and fast.



Key Features

  • Full support for the WebSocket protocol (RFC 6455).
  • Simple and intuitive API.
  • Support for text and binary messages.
  • Automatic ping/pong management to maintain the connection.
  • Ability to check the request origin (Origin).
  • Support for message compression (permessage-deflate).
  • Work with TLS/HTTPS.
  • High performance and low memory consumption.


Installation

To install the library, run the command:

go get github.com/gorilla/websocket

After that, import the package into your code:

import "github.com/gorilla/websocket"


WebSocket server example in Go

Below is a simple server that accepts WebSocket connections and sends received messages back (echo server):



package main

import ( "fmt" "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 echoHandler(w http.ResponseWriter, r *http.Request) { // Upgrade to WebSocket connection 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 message: %s", message)

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

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


WebSocket client in Go

Example of a simple client that connects to the server and sends a message:



package main

import ( "fmt" "log" "net/url"

"github.com/gorilla/websocket")

func main() { u := url.URL{Scheme: "ws", Host: "localhost:8080", Path: "/echo"} fmt.Printf("Connecting to %s", u.String())

conn, _, err := websocket.DefaultDialer.Dial(u.String(), nil) if err != nil { log.Fatal("Connection error:", err) } defer conn.Close()

// Send a text message err = conn.WriteMessage(websocket.TextMessage, []byte("Hello, WebSocket!")) if err != nil { log.Fatal("Send error:", err) }

// Read the response _, message, err := conn.ReadMessage() if err != nil { log.Fatal("Read error:", err) } fmt.Printf("Received response: %s", message)}


Working with multiple clients (broadcast)

To create a chat or notification system, it is often necessary to broadcast messages

Recommendations