BudiBadu Logo

Samplebadu

Code with Example
BudiBadu Logo
Samplebadu

Go by Example: WebSockets

Go 1.23

Implement real-time, bidirectional communication using WebSockets in Go. This example uses the robust `gorilla/websocket` library to create a simple echo server, demonstrating the upgrade process and message handling loop.

Code

package main

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

var upgrader = websocket.Upgrader{
    ReadBufferSize:  1024,
    WriteBufferSize: 1024,
}

func echo(w http.ResponseWriter, r *http.Request) {
    conn, _ := upgrader.Upgrade(w, r, nil)
    defer conn.Close()

    for {
        // Read message from browser
        msgType, msg, err := conn.ReadMessage()
        if err != nil {
            return
        }

        // Print the message to the console
        fmt.Printf("%s sent: %s\n", conn.RemoteAddr(), string(msg))

        // Write message back to browser
        if err = conn.WriteMessage(msgType, msg); err != nil {
            return
        }
    }
}

func main() {
    http.HandleFunc("/echo", echo)
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        http.ServeFile(w, r, "index.html")
    })

    http.ListenAndServe(":8080", nil)
}

Explanation

WebSockets enable real-time, bidirectional communication over a single TCP connection. While Go has a legacy websocket package in x/net, the community standard is github.com/gorilla/websocket due to its stability and feature completeness.

Implementing WebSockets involves an "Upgrade" process where a standard HTTP request is promoted to a WebSocket connection. Once upgraded, the connection persists, allowing you to read and write messages asynchronously.

Security Note: Always configure the CheckOrigin field in your Upgrader. By default, it blocks requests from different origins to prevent Cross-Site WebSocket Hijacking. In production, you should verify that the Origin header matches your trusted domains.

Code Breakdown

9-11
The Upgrader struct configures how HTTP connections are upgraded to WebSocket connections. ReadBufferSize and WriteBufferSize control the buffer sizes for I/O operations. You can also set CheckOrigin here to validate the origin of requests.
15
upgrader.Upgrade performs the WebSocket handshake, upgrading the HTTP connection to the WebSocket protocol. It returns a *websocket.Conn which you use to read and write messages. The third parameter (nil here) can contain HTTP response headers.
16
Deferring conn.Close() ensures the WebSocket connection is properly closed when the function exits, releasing resources and notifying the client.
20
conn.ReadMessage() blocks until a message is received from the client. It returns the message type (text or binary), the message payload as a byte slice, and any error that occurred.
26
Logging the received message to the server console, showing which client sent it using conn.RemoteAddr().
29
conn.WriteMessage() sends a message back to the client. We echo the same message type and payload that we received, creating a simple echo server.