The Gorilla WebSocket package provides a complete implementation of the WebSocket protocol, allowing Go developers to build robust WebSocket applications. This article will guide you through the basics of setting up a WebSocket server and a client using this package.

Setting Up Your Go Environment

Before you begin, ensure you have Go installed on your machine. You can download it from the official Go website.

Installing Gorilla WebSocket

To install the Gorilla WebSocket package, run the following command in your terminal:

go get -u github.com/gorilla/websocket

Creating a Simple WebSocket Server

Below is an example of a simple WebSocket server using the Gorilla WebSocket package:

package main

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

var upgrader = websocket.Upgrader{
    CheckOrigin: func(r *http.Request) bool {
        return true
    },
}

func handleConnections(w http.ResponseWriter, r *http.Request) {
    // Upgrade initial GET request to a websocket
    ws, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        fmt.Println(err)
        return
    }
    defer ws.Close()

    for {
        // read in a message
        messageType, p, err := ws.ReadMessage()
        if err != nil {
            fmt.Println(err)
            break
        }
        // print out that message for clarity
        fmt.Printf("Received: %s\n", p)
    }
}

func main() {
    http.HandleFunc("/ws", handleConnections)
    fmt.Println("Server started on :8080")
    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        fmt.Println("ListenAndServe: ", err)
    }
}

This server listens for WebSocket connections on port 8080. When a connection is upgraded from HTTP to WebSocket, it continuously reads and prints incoming messages.

Creating a WebSocket Client

Now, let's create a WebSocket client that connects to our server:

package main

import (
    "log"
    "os"
    "os/signal"
    "github.com/gorilla/websocket"
)

func main() {
    var addr = "localhost:8080"
    c, _, err := websocket.DefaultDialer.Dial("ws://"+addr+"/ws", nil)
    if err != nil {
        log.Fatal("dial:", err)
    }
    defer c.Close()

    done := make(chan struct{})

    go func() {
        defer c.Close()
        defer close(done)
        for {
            _, message, err := c.ReadMessage()
            if err != nil {
                log.Println("read:", err)
                return
            }
            log.Printf("Received: %s", message)
        }
    }()

    interrupt := make(chan os.Signal, 1)
    signal.Notify(interrupt, os.Interrupt)

    <-interrupt
    log.Println("interrupt")

    err = c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
    if err != nil {
        log.Println("write close:", err)
        return
    }

    select {
    case <-response:
    case <-interrupt:
    }
}

This client connects to the server at localhost:8080 and listens for messages. It cleanly shuts down the connection upon receiving an interrupt signal (Ctrl+C).

Conclusion

The Gorilla WebSocket package in Go is a powerful tool for building WebSocket-based applications. With correct setup and understanding, you can create seamless real-time communication channels. This guide provided a foundation—you are encouraged to explore further the customization capabilities it offers.