or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

client.mdconnection.mdhandlers.mdindex.mdserver.mdtypes.md
tile.json

tessl/golang-github-com-gorilla--websocket

Gorilla WebSocket is a Go implementation of the WebSocket protocol defined in RFC 6455

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
golangpkg:golang/github.com/gorilla/websocket@v1.5.3

To install, run

npx @tessl/cli install tessl/golang-github-com-gorilla--websocket@1.5.0

index.mddocs/

Gorilla WebSocket

Gorilla WebSocket is a Go implementation of the WebSocket protocol defined in RFC 6455, providing a complete and production-ready implementation for both client and server WebSocket connections. It enables bidirectional communication between clients and servers with support for text and binary messages, control messages (close, ping, pong), concurrent operations, and optional per-message compression.

Package Information

  • Package Name: websocket
  • Package Type: golang
  • Module Path: github.com/gorilla/websocket
  • Language: Go
  • Installation: go get github.com/gorilla/websocket

Core Imports

import "github.com/gorilla/websocket"

Or import specific types:

import (
    "github.com/gorilla/websocket"
)

// Access types via package name
var upgrader = websocket.Upgrader{}
var conn *websocket.Conn

Basic Usage

Server Example

package main

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

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

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

    for {
        messageType, p, err := conn.ReadMessage()
        if err != nil {
            log.Println(err)
            return
        }
        if err := conn.WriteMessage(messageType, p); err != nil {
            log.Println(err)
            return
        }
    }
}

func main() {
    http.HandleFunc("/ws", handler)
    log.Fatal(http.ListenAndServe(":8080", nil))
}

Client Example

package main

import (
    "log"
    "net/url"
    "github.com/gorilla/websocket"
)

func main() {
    u := url.URL{Scheme: "ws", Host: "localhost:8080", Path: "/ws"}

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

    // Send a message
    err = conn.WriteMessage(websocket.TextMessage, []byte("Hello"))
    if err != nil {
        log.Fatal(err)
    }

    // Read response
    _, message, err := conn.ReadMessage()
    if err != nil {
        log.Fatal(err)
    }
    log.Printf("Received: %s", message)
}

Architecture

The package is organized around the following key components:

  • Conn: The central type representing a WebSocket connection, providing methods for reading/writing messages and managing connection lifecycle
  • Upgrader: Server-side component for upgrading HTTP connections to WebSocket
  • Dialer: Client-side component for establishing WebSocket connections
  • Message Types: Constants for text, binary, and control messages (close, ping, pong)
  • Buffer Management: Configurable buffering with optional pooling for efficient memory usage

Protocol Features

  • RFC 6455 Compliance: Full implementation of the WebSocket protocol, validated against Autobahn Test Suite
  • Message Types: Support for text (UTF-8), binary, and control messages
  • Concurrency: One concurrent reader and one concurrent writer per connection
  • Compression: Experimental per-message compression support (RFC 7692)
  • Origin Checking: Built-in origin validation for security
  • Subprotocols: Negotiation of application-level protocols

Capabilities

Server-Side WebSocket

Upgrade HTTP connections to WebSocket connections on the server side, with full control over handshake parameters, origin checking, and buffer configuration.

type Upgrader struct {
    HandshakeTimeout  time.Duration
    ReadBufferSize    int
    WriteBufferSize   int
    WriteBufferPool   BufferPool
    Subprotocols      []string
    Error             func(w http.ResponseWriter, r *http.Request, status int, reason error)
    CheckOrigin       func(r *http.Request) bool
    EnableCompression bool
}

func (u *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header) (*Conn, error)

Server-Side WebSocket

Client-Side WebSocket

Establish WebSocket connections to servers with support for custom headers, proxy configuration, TLS settings, and connection timeouts.

type Dialer struct {
    NetDial            func(network, addr string) (net.Conn, error)
    NetDialContext     func(ctx context.Context, network, addr string) (net.Conn, error)
    NetDialTLSContext  func(ctx context.Context, network, addr string) (net.Conn, error)
    Proxy              func(*http.Request) (*url.URL, error)
    TLSClientConfig    *tls.Config
    HandshakeTimeout   time.Duration
    ReadBufferSize     int
    WriteBufferSize    int
    WriteBufferPool    BufferPool
    Subprotocols       []string
    EnableCompression  bool
    Jar                http.CookieJar
}

func (d *Dialer) Dial(urlStr string, requestHeader http.Header) (*Conn, *http.Response, error)
func (d *Dialer) DialContext(ctx context.Context, urlStr string, requestHeader http.Header) (*Conn, *http.Response, error)

Client-Side WebSocket

Connection Management and I/O

Read and write messages using byte slices or streaming interfaces, with support for control messages, deadlines, and message handlers.

type Conn struct {
    // unexported fields
}

// Reading messages
func (c *Conn) ReadMessage() (messageType int, p []byte, err error)
func (c *Conn) NextReader() (messageType int, r io.Reader, err error)
func (c *Conn) ReadJSON(v interface{}) error

// Writing messages
func (c *Conn) WriteMessage(messageType int, data []byte) error
func (c *Conn) NextWriter(messageType int) (io.WriteCloser, error)
func (c *Conn) WriteJSON(v interface{}) error
func (c *Conn) WriteControl(messageType int, data []byte, deadline time.Time) error
func (c *Conn) WritePreparedMessage(pm *PreparedMessage) error

// Connection control
func (c *Conn) Close() error
func (c *Conn) SetReadDeadline(t time.Time) error
func (c *Conn) SetWriteDeadline(t time.Time) error
func (c *Conn) SetReadLimit(limit int64)

Connection Management and I/O

Message Handlers and Control

Customize handling of control messages (close, ping, pong) and enable compression for message payloads.

// Handler functions
func (c *Conn) SetCloseHandler(h func(code int, text string) error)
func (c *Conn) SetPingHandler(h func(appData string) error)
func (c *Conn) SetPongHandler(h func(appData string) error)
func (c *Conn) CloseHandler() func(code int, text string) error
func (c *Conn) PingHandler() func(appData string) error
func (c *Conn) PongHandler() func(appData string) error

// Compression
func (c *Conn) EnableWriteCompression(enable bool)
func (c *Conn) SetCompressionLevel(level int) error

Message Handlers and Control

Constants and Types

Message type constants, close codes, error types, and helper functions for working with WebSocket connections.

// Message types
const (
    TextMessage   = 1
    BinaryMessage = 2
    CloseMessage  = 8
    PingMessage   = 9
    PongMessage   = 10
)

// Close codes
const (
    CloseNormalClosure           = 1000
    CloseGoingAway               = 1001
    CloseProtocolError           = 1002
    CloseUnsupportedData         = 1003
    CloseNoStatusReceived        = 1005
    CloseAbnormalClosure         = 1006
    CloseInvalidFramePayloadData = 1007
    ClosePolicyViolation         = 1008
    CloseMessageTooBig           = 1009
    CloseMandatoryExtension      = 1010
    CloseInternalServerErr       = 1011
    CloseServiceRestart          = 1012
    CloseTryAgainLater           = 1013
    CloseTLSHandshake            = 1015
)

Constants and Types

Concurrency

The library supports one concurrent reader and one concurrent writer per connection. Applications must ensure:

  • No more than one goroutine calls read methods concurrently
  • No more than one goroutine calls write methods concurrently
  • Close() and WriteControl() can be called concurrently with all other methods

Error Handling

The package defines several error types:

  • ErrBadHandshake: Returned when server response to opening handshake is invalid
  • ErrCloseSent: Returned when writing after sending a close message
  • ErrReadLimit: Returned when reading a message larger than the read limit
  • CloseError: Represents a close message with code and optional text
  • HandshakeError: Describes an error with the handshake from the peer