Skip to main content

Overview

The websocket middleware handles WebSocket upgrade requests, enabling real-time bidirectional communication between clients and your server.

Installation

Quick Start

Configuration

Examples

Echo Server

Chat Application

Origin Validation

Custom Origin Check

Subprotocols

Binary Messages

Ping/Pong

Message Types

Conn Methods

API Reference

Client Example

Technical Details

WebSocket Protocol Implementation

The middleware implements the WebSocket protocol (RFC 6455) with the following key components:

Connection Upgrade Process

  1. Request Validation: Checks for Upgrade: websocket and Connection: Upgrade headers
  2. Origin Validation: Validates the request origin against configured allowed origins
  3. Key Exchange: Validates Sec-WebSocket-Key and computes the accept key using SHA1 hash with the WebSocket GUID
  4. Subprotocol Negotiation: Matches requested subprotocols with supported ones
  5. HTTP Hijacking: Takes over the HTTP connection using Go’s http.Hijacker interface
  6. 101 Switching Protocols: Sends the upgrade response with Sec-WebSocket-Accept header

Frame Structure

The implementation handles WebSocket frames with the following structure:
  • Opcode: Identifies the frame type (text, binary, close, ping, pong)
  • Masking: Client-to-server messages must be masked; server-to-client messages are unmasked
  • Payload Length: Supports three length encoding formats:
    • 0-125 bytes: Single byte length
    • 126-65535 bytes: 2-byte extended length
    • 65536+ bytes: 8-byte extended length

Connection Management

  • Thread-Safe Writes: Uses mutex locks to ensure concurrent write safety
  • Buffered I/O: Utilizes bufio.Reader and bufio.Writer for efficient data transfer
  • Resource Cleanup: Automatically closes underlying TCP connections when handlers return
  • Error Handling: Returns errors for invalid frames, connection failures, and protocol violations

Security Features

  • SHA1 for Key Exchange: Uses SHA1 (required by RFC 6455) for computing the Sec-WebSocket-Accept header
  • Origin Validation: Supports both whitelist-based and custom validation functions
  • Wildcard Origins: Allows * for development but should be restricted in production
  • No Server Masking: Server messages are sent unmasked per protocol specification

Best Practices

  • Always validate origins in production
  • Handle disconnections gracefully
  • Use ping/pong for connection health
  • Clean up resources when connections close
  • Consider using a message broker for scaling

Testing

The middleware includes comprehensive test coverage for all major functionality:
  • sse - Server-Sent Events
  • timeout - Request timeout