Sling Academy
Home/Golang/Using Gorilla WebSocket Package for Robust WebSocket Applications in Go

Using Gorilla WebSocket Package for Robust WebSocket Applications in Go

Last updated: November 26, 2024

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.

Next Article: Handling WebSocket Connections and Lifecycle Events in Go

Previous Article: Broadcasting Messages to Multiple Clients with WebSockets in Go

Series: Websocket & Chat Programs in Go

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant