View : 0

12/04/2026 18:15pm

Ep.26 Go and Compression on WebSocket - Reducing Data Size, Increasing Speed!

Ep.26 Go and Compression on WebSocket - Reducing Data Size, Increasing Speed!

#Go

#Golang

#Go language

#Go Programming

#Compression

#WebSocket

#Reduce Data Size

#Increase Speed

#Per-Message Deflate

#Programming Education

#Practice programming

#programming for beginners

#programming language

#programming

#programmers

#Superdev School

Go and Compression on WebSocket - Reducing Data Size, Increasing Speed!

In this episode, we will learn about Compression on WebSocket to help reduce the size of data transmitted over the network and enhance the efficiency of communication in your system.

 

What is Compression?

Compression is the process of reducing the size of data before sending it to the destination in order to :

  1. Reduce bandwidth usage
  2. Increase data transmission speed
  3. Decrease latency

 

Benefits of Compression on WebSocket

  • Suitable for large data sizes, such as JSON or long messages
  • Increases data loading speed for bandwidth-constrained networks
  • Reduces costs, especially in systems that charge based on bandwidth usage

 

Using Per-Message Deflate on WebSocket

Per-Message Deflate is one of the standard data compression methods supported in WebSocket and can be easily implemented in Go using the package github.com/gorilla/websocket

 

Steps to Enable Compression

1. Use EnableCompression to activate compression.

2. Use SetCompressionLevel to specify the level of compression.

In this example :

Enable compression with EnableCompression: true.

WebSocket will automatically compress data when sending messages between the server and client.

Example of Enabling Compression on WebSocket Server

package main

import (
    "log"
    "net/http"

    "github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{
    CheckOrigin: func(r *http.Request) bool {
        return true
    },
    EnableCompression: true, // เปิดใช้งาน Compression
}

func handleConnections(w http.ResponseWriter, r *http.Request) {
    conn, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        log.Println("Error upgrading connection:", err)
        return
    }
    defer conn.Close()

    log.Println("New client connected")

    for {
        _, msg, err := conn.ReadMessage()
        if err != nil {
            log.Println("Error reading message:", err)
            break
        }
        log.Printf("Received: %s", msg)

        if err := conn.WriteMessage(websocket.TextMessage, msg); err != nil {
            log.Println("Error writing message:", err)
            break
        }
    }
}

func main() {
    http.HandleFunc("/ws", handleConnections)

    log.Println("WebSocket server with compression started at :8080/ws")
    http.ListenAndServe(":8080", nil)
}

 

Configuring Compression Level

To adjust the level of compression, you can use SetCompressionLevel from the compress/flate package: Recommended compression levels :

flate.BestSpeed: for fast compression

flate.BestCompression: for maximum compression

flate.DefaultCompression: for standard setting

import "compress/flate"

// ตั้งค่าระดับการบีบอัด
conn.SetCompressionLevel(flate.BestCompression) // บีบอัดสูงสุด

 

Enabling Compression on WebSocket Client

The WebSocket Client must also support compression. In the JavaScript WebSocket API, automatic compression is supported if the server has it enabled.

Client-side code example :

const socket = new WebSocket("ws://localhost:8080/ws");

socket.onopen = () => {
    console.log("Connected to server with compression");
    socket.send("Hello from client!");
};

socket.onmessage = (event) => {
    console.log("Received:", event.data);
};

 

Checking Compression

1. Using Wireshark or DevTools

Use Wireshark to capture packet data and observe the data size. Use the Developer Tools of the browser to inspect WebSocket traffic.

2. Logging Message Size Before and After Compression

You can log the message size to see the results of the compression :

Example :

log.Printf("Original size: %d bytes", len(originalMessage))
log.Printf("Compressed size: %d bytes", len(compressedMessage))

 

In Summary

  • Compression helps reduce data size and increase communication speed.
  • Use EnableCompression to activate compression on WebSocket.
  • Adjust the compression level with SetCompressionLevel to suit your needs.