ws

package
v0.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 8, 2026 License: MIT Imports: 21 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package ws is the WebSocket protocol (RFC 6455) after the handshake, as the profile's browser speaks it: framing, permessage-deflate through internal/zdeflate, HTTP/2 DATA packing, pings and the close handshake. It also checks a socket's URL and subprotocols as the WebSocket constructor does, makes the handshake's key, and checks the server's answer (status, accept key, subprotocol, extensions).

Every client message is one final frame, masked with a fresh key, its length in the shortest form. The transport underneath (an HTTP/1.1 connection or an HTTP/2 stream) is the caller's, behind Transport.

Index

Constants

View Source
const (
	OpContinuation byte = 0x0
	OpText         byte = 0x1
	OpBinary       byte = 0x2
	OpClose        byte = 0x8
	OpPing         byte = 0x9
	OpPong         byte = 0xa
)

Frame opcodes (RFC 6455, section 5.2).

View Source
const (
	// MaxMessage bounds a message's payload, inflated or not.
	MaxMessage = 64 << 20
)

Limits on what the server sends, so a hostile one cannot make the socket buffer without bound. Browsers' own limits were not measured.

Variables

View Source
var ErrClosing = errors.New("ws: the socket is closing")

ErrClosing is a message written after the socket sent its close frame.

Functions

func AcceptKey

func AcceptKey(key string) string

AcceptKey is the Sec-WebSocket-Accept a server answers key with.

func AppendHeader

func AppendHeader(b []byte, h Header) []byte

AppendHeader appends h's encoding to b, its length in the shortest form, as every browser writes it (7, 16 or 64 bits).

func CheckProtocols

func CheckProtocols(protocols []string) error

CheckProtocols checks subprotocols as the WebSocket constructor does: tokens (RFC 7230), none twice.

func FailedResponse

func FailedResponse(resp *http.Response) *http.Response

FailedResponse returns resp with the start of its body read into memory and the transport behind it closed.

func MaskBytes

func MaskBytes(key [4]byte, p []byte)

MaskBytes masks (or unmasks) payload p in place with key.

func NewKey

func NewKey(rand io.Reader) (string, error)

NewKey returns a Sec-WebSocket-Key: 16 bytes from rand, in base64.

func PlacesProtocols

func PlacesProtocols(headers, http1 []profile.Header) bool

PlacesProtocols reports whether a handshake's lists, over HTTP/2 and HTTP/1.1 (its plan's Headers and HTTP1), both have a place for Sec-WebSocket-Protocol. An empty list, one never sent over, has.

func Target

func Target(u *url.URL) (*url.URL, error)

Target checks a WebSocket URL as the WebSocket constructor does (ws or wss, no fragment) and returns the http or https URL its handshake requests, which cookies, sites and connections use.

Types

type CloseError

type CloseError struct {
	Code   int
	Reason string
}

CloseError is the close frame that ended a socket: the server's, or its echo of ours. Code is 1005 for a close frame without one.

func (*CloseError) Error

func (e *CloseError) Error() string

type Compressor

type Compressor struct {
	// contains filtered or unexported fields
}

Compressor compresses a socket's messages as the profile's browser does once the server accepted permessage-deflate, including which messages it sends uncompressed. It is not safe for concurrent use.

func NewCompressor

func NewCompressor(p *profile.WebSocket, d *Deflate) (*Compressor, error)

NewCompressor returns the compressor of p's browser for d. It fails where the browser fails the socket: client_max_window_bits=8, which zlib refuses and only Chrome raises to 9.

func (*Compressor) Message

func (c *Compressor) Message(p []byte) ([]byte, bool)

Message returns what goes on the wire for message p, and whether it is compressed (RSV1).

type Config

type Config struct {
	Profile *profile.WebSocket
	// Name is the profile's, for errors.
	Name string
	// H2 is set for an HTTP/2 stream; MaxData is then the most a DATA
	// frame carries (the profile's cap, or the peer's frame size).
	H2      bool
	MaxData int
	// Deflate is permessage-deflate as accepted, or nil.
	Deflate *Deflate
	Clock   clockwork.Clock
	// Rand draws masking keys (crypto/rand).
	Rand io.Reader
}

Config is how a socket speaks: the profile's browser, on HTTP/2 or HTTP/1.1, with the extensions the server accepted.

type Conn

type Conn struct {
	// contains filtered or unexported fields
}

Conn is one WebSocket after its handshake, framed, compressed and closed as the profile's browser does. A goroutine reads the server's frames from the start, so pings are answered even without ReadMessage.

func New

func New(t Transport, r io.Reader, cfg Config) (*Conn, error)

New runs a socket on t. r reads what follows the handshake: an HTTP/1.1 connection's buffered reader, which may already hold server frames, or t. It fails, sending nothing, where the browser fails the socket (a compression window it cannot use); the caller ends t.

func (*Conn) Close

func (c *Conn) Close(code int, reason string) error

Close starts the close handshake, unless started, and returns once it is done and, where the browser's close event waits for it, the transport has ended. A server whose close never comes has the transport ended after closeTimeout.

func (*Conn) ReadMessage

func (c *Conn) ReadMessage(ctx context.Context) (Message, error)

ReadMessage returns the next data message, or once the socket closed a *CloseError (the close handshake) or the error that ended it.

func (*Conn) WriteMessage

func (c *Conn) WriteMessage(ctx context.Context, opcode byte, p []byte) error

WriteMessage sends p as one message of opcode (text or binary), in a single frame with its length in the shortest form, compressed where the profile's browser compresses it.

type Deflate

type Deflate struct {
	// ServerNoContextTakeover: each server message is compressed on its
	// own. ClientNoContextTakeover: the server asks ours to be.
	ServerNoContextTakeover bool
	ClientNoContextTakeover bool
	// ClientMaxWindowBits is the LZ77 window our messages may use: 15
	// unless the server limited it.
	ClientMaxWindowBits int
}

Deflate is permessage-deflate as the server accepted it (RFC 7692, section 7.1).

func CheckHandshake

func CheckHandshake(resp *http.Response, h2 bool, key, offer string, protocols []string) (*Deflate, error)

CheckHandshake checks the server's answer resp to a handshake with key, offer and protocols, over HTTP/2 when h2 (RFC 6455, section 4.1; RFC 8441, section 5), and returns the permessage-deflate it accepted, if any.

func ParseExtensions

func ParseExtensions(offer, answer string) (*Deflate, error)

ParseExtensions reads the server's Sec-WebSocket-Extensions answer to our offer: nil for none, the accepted permessage-deflate, or an error for anything not offered (RFC 7692, section 7.1). An unoffered client_max_window_bits is accepted, as every browser accepts it.

type Header struct {
	Fin bool
	// RSV holds RSV1 to RSV3 as the first byte carries them (0x40, 0x20,
	// 0x10).
	RSV    byte
	Opcode byte
	Masked bool
	Mask   [4]byte
	Length int64
}

Header is a frame's header as on the wire.

func ReadHeader

func ReadHeader(r io.Reader) (Header, error)

ReadHeader reads a frame header from r. It returns io.EOF only when r ends before the frame starts. Reserved opcodes, fragmented or long control frames and lengths of 2^63 or more are errors (RFC 6455, 5.2 and 5.5); an overlong length form is accepted.

type Message

type Message struct {
	Opcode  byte
	Payload []byte
}

Message is one data message the server sent.

type Transport

type Transport interface {
	// Read reads what the server sent; an error once it ended the
	// transport (io.EOF: closed the connection, or ended its stream).
	io.Reader
	// Send writes one frame as parts: over HTTP/2 each part goes in DATA
	// frames of its own (cut at the DATA cap and the flow-control
	// windows), the last with END_STREAM when end; over HTTP/1.1 they go
	// together. A failed Send may have written part of the frame.
	Send(ctx context.Context, parts [][]byte, end bool) error
	// Close ends the transport now: it closes the TCP connection, or
	// resets the stream (RST_STREAM NO_ERROR) unless both sides ended it.
	Close() error
	// Release frees the transport once the server ended it, sending
	// nothing more.
	Release()
}

Transport carries a socket's frames: an HTTP/1.1 connection after its 101, or an HTTP/2 extended CONNECT stream (RFC 8441).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL