Convert Figma logo to code with AI

gorilla logowebsocket

Package gorilla/websocket is a fast, well-tested and widely used WebSocket implementation for Go.

22,033
3,466
22,033
40

Top Related Projects

6,094

Tiny WebSocket library for Go.

Real-time messaging library for Go. The simplest way to add feature-rich and scalable WebSocket support to your application. The core of Centrifugo server.

Quick Overview

The gorilla/websocket is a Go implementation of the WebSocket protocol. It provides a simple and efficient way to create and manage WebSocket connections in Go applications. The library supports both client and server-side WebSocket communication, making it a versatile tool for building real-time, bidirectional communication systems.

Pros

  • Simplicity: The library provides a straightforward and easy-to-use API, making it accessible for developers of all skill levels.
  • Performance: The gorilla/websocket library is designed to be highly efficient, with low overhead and fast message processing.
  • Compatibility: The library is compatible with the latest WebSocket protocol specifications and can be used with a wide range of client-side and server-side technologies.
  • Flexibility: The library allows for customization and extension, enabling developers to tailor the WebSocket functionality to their specific needs.

Cons

  • Limited Documentation: While the library is well-designed, the documentation could be more comprehensive, especially for more advanced use cases.
  • Lack of Automatic Reconnection: The library does not provide built-in support for automatic reconnection of WebSocket connections, which may be a requirement for some applications.
  • Dependency on External Libraries: The gorilla/websocket library depends on other external libraries, which may introduce additional complexity and potential issues.
  • Potential Performance Concerns: While the library is generally performant, large-scale applications with high WebSocket traffic may require additional optimization or the use of more specialized WebSocket solutions.

Code Examples

Here are a few code examples demonstrating the usage of the gorilla/websocket library:

Establishing a WebSocket Connection (Server-side)

package main

import (
    "fmt"
    "log"
    "net/http"

    "github.com/gorilla/websocket"
)

func main() {
    http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
        conn, err := upgradeToWebSocket(w, r)
        if err != nil {
            log.Println("Failed to upgrade to WebSocket:", err)
            return
        }

        // Handle WebSocket communication here
        handleWebSocketConnection(conn)
    })

    log.Println("Starting server on :8080")
    log.Fatal(http.ListenAndServe(":8080", nil))
}

func upgradeToWebSocket(w http.ResponseWriter, r *http.Request) (*websocket.Conn, error) {
    upgrader := websocket.Upgrader{
        ReadBufferSize:  1024,
        WriteBufferSize: 1024,
    }
    return upgrader.Upgrade(w, r, nil)
}

func handleWebSocketConnection(conn *websocket.Conn) {
    defer conn.Close()

    for {
        _, message, err := conn.ReadMessage()
        if err != nil {
            log.Println("Error reading message:", err)
            return
        }

        fmt.Printf("Received message: %s\n", message)

        // Echo the message back to the client
        err = conn.WriteMessage(websocket.TextMessage, message)
        if err != nil {
            log.Println("Error writing message:", err)
            return
        }
    }
}

Connecting to a WebSocket Server (Client-side)

package main

import (
    "fmt"
    "log"

    "github.com/gorilla/websocket"
)

func main() {
    conn, _, err := websocket.DefaultDialer.Dial("ws://localhost:8080/ws", nil)
    if err != nil {
        log.Fatalf("Failed to connect to WebSocket: %v", err)
    }
    defer conn.Close()

    // Send a message to the server
    err = conn.WriteMessage(websocket.TextMessage, []byte("Hello, WebSocket!"))
    if err != nil {
        log.Println("Error writing message:", err)
        return
    }

    // Read a message from the server
    _, message, err := conn.ReadMessage()
    if err != nil {
        log.Println("Error reading message:", err)

Competitor Comparisons

6,094

Tiny WebSocket library for Go.

Pros of ws

  • Higher performance and lower memory footprint
  • More flexible and customizable, allowing fine-grained control over WebSocket operations
  • Supports zero-copy upgrades for improved efficiency

Cons of ws

  • Less feature-rich out of the box compared to websocket
  • Steeper learning curve due to its low-level nature
  • Requires more manual implementation for common WebSocket functionalities

Code Comparison

websocket:

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

ws:

conn, _, _, err := ws.DefaultDialer.Dial(context.Background(), u.String())
if err != nil {
    log.Fatal("dial:", err)
}
defer conn.Close()

Both libraries provide similar basic functionality for establishing WebSocket connections. However, ws offers more granular control over the connection process, while websocket provides a simpler, more straightforward API.

websocket is generally easier to use and offers more built-in features, making it suitable for most common WebSocket applications. On the other hand, ws excels in performance-critical scenarios and situations requiring fine-tuned control over WebSocket operations, albeit with a steeper learning curve.

Real-time messaging library for Go. The simplest way to add feature-rich and scalable WebSocket support to your application. The core of Centrifugo server.

Pros of Centrifuge

  • Built-in support for real-time messaging patterns like pub/sub and presence
  • Scalable architecture with support for multiple server nodes
  • Includes features like automatic reconnection and message recovery

Cons of Centrifuge

  • Higher complexity and learning curve compared to a simpler WebSocket library
  • May be overkill for basic WebSocket communication needs
  • Requires additional server-side setup and configuration

Code Comparison

Centrifuge client connection:

client := centrifuge.NewClient("ws://localhost:8000/connection/websocket")
client.OnConnect(func(c *centrifuge.Client) {
    fmt.Println("Connected")
})
client.Connect()

Gorilla WebSocket connection:

conn, _, err := websocket.DefaultDialer.Dial("ws://localhost:8000/ws", nil)
if err != nil {
    log.Fatal("dial:", err)
}
defer conn.Close()

Summary

Centrifuge offers a more comprehensive real-time messaging solution with built-in scalability and advanced features, while Gorilla WebSocket provides a simpler, low-level WebSocket implementation. Choose Centrifuge for complex real-time applications requiring scalability and advanced messaging patterns. Opt for Gorilla WebSocket for basic WebSocket communication or when you need more control over the implementation details.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Gorilla WebSocket

GoDoc CircleCI

Gorilla WebSocket is a Go implementation of the WebSocket protocol.

Documentation

Status

The Gorilla WebSocket package provides a complete and tested implementation of the WebSocket protocol. The package API is stable.

Installation

go get github.com/gorilla/websocket

Protocol Compliance

The Gorilla WebSocket package passes the server tests in the Autobahn Test Suite using the application in the examples/autobahn subdirectory.