websocket

package
v1.81.0 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: MIT Imports: 26 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.

README

websocket

Package websocket implements the WebSocket protocol (RFC 6455) for fasthttp servers and clients, with optional permessage-deflate compression (RFC 7692).

import "github.com/valyala/fasthttp/websocket"

Server

func handler(ctx *fasthttp.RequestCtx) {
	err := websocket.Accept(ctx, nil, func(c *websocket.Conn) {
		for {
			typ, msg, err := c.Read(c.Context())
			if err != nil {
				return
			}
			if err := c.Write(c.Context(), typ, msg); err != nil {
				return
			}
		}
	})
	if err != nil {
		// Not a WebSocket handshake: Accept has written the error response.
		log.Printf("websocket: %v", err)
	}
}

The function given to Accept runs on the upgraded connection once the request handler returns, and the connection is closed when it returns.

Client

c, err := websocket.Dial(ctx, "wss://example.com/echo", nil)
if err != nil {
	return err
}
defer c.CloseNow()

if err := c.Write(ctx, websocket.MessageText, []byte("hello")); err != nil {
	return err
}
_, msg, err := c.Read(ctx)
if err != nil {
	return err
}
fmt.Printf("%s\n", msg)

return c.Close(ctx, websocket.StatusNormalClosure, "")

Usage notes

  • Messages. Read and Write handle a whole message; Reader and Writer stream one. The bytes Read returns stay valid until the next Read or Reader call.
  • Contexts and timeouts. Reads and writes take a context. One that is cancelled or times out during I/O closes the connection, since the frame stream cannot be resumed. ReadTimeout and WriteTimeout in the options bound each read and frame write without a timeout context for each call.
  • Closing. Close performs the closing handshake; CloseNow closes at once. A closed connection returns the error that closed it: CloseStatus(err) gives the status code of a closing handshake or protocol violation.
  • Concurrency. Read, Reader and CloseRead must not be called concurrently with each other, and a reader from Reader or a writer from Writer is for one goroutine at a time. All other Conn methods may be called concurrently.
  • Write-only connections. CloseRead reads in the background, so that pings are answered and the peer's Close frame is seen. Ping checks that the peer still answers.
  • Origin. A request with an Origin header is accepted only when its host and port equal the request's Host, unless AcceptOptions.CheckOrigin decides.
  • Compression. Off by default; CompressionMode in the options enables it, with or without context takeover.
  • Limits. MaxMessageSize bounds a received message, 4 MiB by default.
  • Server settings. The timeouts and Shutdown of fasthttp.Server do not apply to an upgraded connection.

See the package documentation for the full API.

Documentation

Overview

Package websocket implements the WebSocket protocol (RFC 6455) on top of fasthttp.

Servers call Accept from a fasthttp request handler; applications served through fasthttpadaptor call it from a fasthttp handler, not from the adapted net/http one. Clients call Dial.

Conn methods take a context for cancellation and deadlines. A read or write that is cancelled or times out closes the connection, since the frame stream cannot be resumed. One that gives up before its operation starts, while waiting for another call, leaves it open; a read with a Pong to send and a Conn.Writer with part of its message sent have started. ReadTimeout and WriteTimeout in the options bound each read and frame write without wrapping each context; see AcceptOptions.

Once a connection is closed, reads and writes return the error that closed it. A closing handshake, a protocol violation by the peer or a transport that failed without a Close frame yield a CloseError value, the last with StatusAbnormalClosure: inspect it with CloseStatus, or with

var ce CloseError
if errors.As(err, &ce) { ... }

A cancelled or expired context yields its error; ReadTimeout and WriteTimeout yield a timeout error; closing with Conn.CloseNow, or writing after the Close frame has been sent, yields net.ErrClosed.

Compression with permessage-deflate (RFC 7692) is off unless CompressionMode in the options enables it; MaxMessageSize then bounds messages before and after decompression.

Index

Examples

Constants

View Source
const DefaultMaxMessageSize = 4 << 20

DefaultMaxMessageSize is the message size limit used when MaxMessageSize is zero.

Variables

This section is empty.

Functions

func Accept

func Accept(ctx *fasthttp.RequestCtx, opts *AcceptOptions, handler func(*Conn)) error

Accept upgrades the request to a WebSocket connection and arranges for handler to run on it once the request handler returns. The connection is closed when handler returns; calls still in flight on other goroutines fail. Headers set on ctx.Response before the call are sent with the 101 response, except those of the handshake itself and Trailer, which Accept removes or replaces; one stored under a spelling it cannot remove is a server error.

If the request is not a valid WebSocket handshake, Accept writes an error response and returns the reason; the caller should then return without touching the response.

fasthttp skips the upgrade while shutting down with fasthttp.Server.CloseOnShutdown. The Server's timeouts and Shutdown do not apply to the upgraded connection; use the options here instead. The connection's TCP or Unix socket is closed with the WebSocket connection. A connection that hides its socket, as with fasthttp.Server.MaxConnsPerIP without TLS or a net.Conn of the caller's, is closed by fasthttp when handler returns, or with the WebSocket connection under fasthttp.Server.KeepHijackedConns.

Example
package main

import (
	"log"

	"github.com/valyala/fasthttp"
	"github.com/valyala/fasthttp/websocket"
)

func main() {
	handler := func(ctx *fasthttp.RequestCtx) {
		err := websocket.Accept(ctx, nil, func(c *websocket.Conn) {
			for {
				typ, msg, err := c.Read(c.Context())
				if err != nil {
					return
				}
				if err := c.Write(c.Context(), typ, msg); err != nil {
					return
				}
			}
		})
		if err != nil {
			log.Printf("websocket: %v", err)
		}
	}
	log.Fatal(fasthttp.ListenAndServe(":8080", handler))
}

Types

type AcceptOptions

type AcceptOptions struct {
	// CheckOrigin reports whether the request's Origin is acceptable. When
	// nil, requests without an Origin header are accepted and all others must
	// carry exactly one Origin of the form scheme://host[:port] whose host and
	// port equal the request Host, compared case-insensitively and without
	// regard to the scheme.
	CheckOrigin func(ctx *fasthttp.RequestCtx) bool

	// Subprotocols lists the supported subprotocols in order of preference.
	// The first one the client also offers is selected; with no match none is.
	// Names must be distinct HTTP tokens.
	Subprotocols []string

	// MaxMessageSize limits the size of a message, counting all its fragments.
	// A larger message closes the connection with [StatusMessageTooBig].
	// Zero means [DefaultMaxMessageSize].
	MaxMessageSize int

	// ReadTimeout bounds every [Conn.Read], [Conn.Reader] and reader Read
	// call, but not [Conn.CloseRead]; WriteTimeout bounds every frame write,
	// but not the wait of [Conn.Ping] for the pong. A call that exceeds its
	// bound once its operation has started closes the connection: a read with
	// a Pong to send and a [Conn.Writer] with part of its message sent have.
	// One that times out before that, while waiting for another call, returns
	// [os.ErrDeadlineExceeded] and leaves it open. Zero means no bound.
	ReadTimeout  time.Duration
	WriteTimeout time.Duration

	// CompressionMode enables permessage-deflate when the client offers it.
	// Zero means [CompressionDisabled].
	CompressionMode CompressionMode

	// CompressionThreshold is the size from which a message is compressed; a
	// [Conn.Writer] message is judged by its first fragment. Zero means 128
	// bytes with context takeover and 512 without.
	CompressionThreshold int
}

AcceptOptions configures Accept. The zero value is valid.

type CloseError

type CloseError struct {
	Reason string
	Code   StatusCode
}

CloseError is the error of a connection closed with a status code.

func (CloseError) Error

func (e CloseError) Error() string

Error returns the status code and reason.

type CompressionMode

type CompressionMode int

CompressionMode selects how permessage-deflate (RFC 7692) is used.

const (
	// CompressionDisabled neither offers nor accepts compression.
	CompressionDisabled CompressionMode = iota

	// CompressionNoContextTakeover compresses each message on its own, with
	// compressors and decompressors taken from pools, so a connection holds
	// no compression state between messages. Small messages gain little.
	CompressionNoContextTakeover

	// CompressionContextTakeover lets messages refer back to earlier ones,
	// which compresses streams of similar small messages well. A connection
	// keeps the last 4 KiB it compressed and the last 32 KiB it decompressed
	// as dictionaries, in buffers of twice that size; the compressors
	// themselves stay pooled. The peer may still decline context takeover for
	// either direction.
	CompressionContextTakeover
)

type Conn

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

Conn is a WebSocket connection.

Read, Reader and CloseRead must not be called concurrently with each other, and a reader from Reader or a writer from Writer is not safe for concurrent use; all other methods may be called concurrently. See the package documentation for the errors a closed connection reports.

func Dial

func Dial(ctx context.Context, u string, opts *DialOptions) (*Conn, error)

Dial connects to the WebSocket server at u, a ws or wss URL (http and https are accepted as aliases) without a fragment, and completes the handshake. ctx bounds the whole of it, apart from a custom DialOptions.Dial. The path is sent as given; user information in the URL becomes a Basic Authorization header unless DialOptions.Header carries one. Redirects are not followed. Interim 1xx responses are skipped; a final response other than 101 is an error, and its status and headers are available through DialOptions.Response.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/valyala/fasthttp/websocket"
)

func main() {
	ctx := context.Background()
	opts := &websocket.DialOptions{ReadTimeout: time.Minute, WriteTimeout: 10 * time.Second}
	c, err := websocket.Dial(ctx, "wss://example.com/echo", opts)
	if err != nil {
		log.Println(err)
		return
	}
	defer c.Close(ctx, websocket.StatusNormalClosure, "")
	if err := c.Write(ctx, websocket.MessageText, []byte("hello")); err != nil {
		log.Println(err)
		return
	}
	_, msg, err := c.Read(ctx)
	if err != nil {
		log.Println(err)
		return
	}
	fmt.Printf("%s\n", msg)
}

func (*Conn) Close

func (c *Conn) Close(ctx context.Context, code StatusCode, reason string) error

Close performs the closing handshake: it sends a Close frame carrying code and reason, waits for the peer's Close frame and closes the connection. The wait ends at the ctx deadline; without one it lasts at most ReadTimeout, or five seconds when that is zero too. Close returns an error only for an invalid code or reason, or when the Close frame could not be sent and the connection is still usable. Otherwise it returns nil once the connection is closed, whether or not the peer answered; context.Cause(c.Context()) tells why.

func (*Conn) CloseNow

func (c *Conn) CloseNow() error

CloseNow closes the connection without a closing handshake.

func (*Conn) CloseRead

func (c *Conn) CloseRead(ctx context.Context)

CloseRead starts a goroutine that reads and handles control frames, so a connection used only for writing still answers pings and sees the peer's Close frame. It runs until the connection is closed, which cancelling ctx does; ReadTimeout does not apply to it. A data message closes the connection with StatusPolicyViolation. Conn.Read and Conn.Reader must not be called afterwards; use Conn.Context to learn when the connection is closed.

func (*Conn) Context

func (c *Conn) Context() context.Context

Context returns a context that is cancelled when the connection is closed. context.Cause reports the error that closed it.

func (*Conn) Ping

func (c *Conn) Ping(ctx context.Context) error

Ping sends a ping and waits for the matching pong. Pongs are only seen while another goroutine is in Conn.Read or Conn.Reader, or after Conn.CloseRead. Only one Ping is in flight at a time.

func (*Conn) Read

func (c *Conn) Read(ctx context.Context) (MessageType, []byte, error)

Read reads one message. The returned bytes are owned by the connection and stay valid until the next Read or Conn.Reader call.

func (*Conn) Reader

func (c *Conn) Reader(ctx context.Context) (MessageType, io.Reader, error)

Reader returns a reader for the next message, whose Read calls are bounded by ctx as well. It is valid until the next Conn.Read or Reader call, which discards whatever is left of the message; it must not be used afterwards.

func (*Conn) Subprotocol

func (c *Conn) Subprotocol() string

Subprotocol returns the negotiated subprotocol, or "" if none was.

func (*Conn) Write

func (c *Conn) Write(ctx context.Context, typ MessageType, p []byte) error

Write sends p as a single-frame message of type typ. The wait for another writer can end through ctx or WriteTimeout without closing the connection.

func (*Conn) Writer

func (c *Conn) Writer(ctx context.Context, typ MessageType) (io.WriteCloser, error)

Writer returns a writer for one message of type typ; ctx also bounds the frames its Write and Close calls send. Data is buffered and sent in fragments; a write larger than the buffer goes out as a fragment of its own, and Close sends what is left as the last one. Only one writer is open at a time: Conn.Write and further Writer calls block until it is closed, which a failed write also does.

type DialOptions

type DialOptions struct {
	// Dial establishes the TCP connection. nil means [net.Dialer], which
	// honors ctx; a custom dialer is bounded only by its own timeouts. The
	// dialers of the fasthttpproxy package can be used directly.
	Dial fasthttp.DialFunc

	// TLSConfig is used for wss URLs. nil means the default configuration.
	// ServerName is taken from the URL when empty.
	TLSConfig *tls.Config

	// Header holds extra request headers. A Host header overrides the URL
	// host; the headers of the handshake itself (Connection, Upgrade,
	// Sec-WebSocket-*, Content-Length, Transfer-Encoding, Trailer) are
	// rejected.
	Header *fasthttp.RequestHeader

	// Response, when not nil, receives the status and headers of the
	// handshake response, also when the handshake fails.
	Response *fasthttp.Response

	// Subprotocols lists the subprotocols to offer, in order of preference.
	// Names must be distinct HTTP tokens.
	Subprotocols []string

	// ReadBufferSize is the size of the buffer the handshake response and
	// then the frames are read through; the response headers must fit in it.
	// Zero means 4096.
	ReadBufferSize int

	// MaxMessageSize, ReadTimeout, WriteTimeout, CompressionMode and
	// CompressionThreshold work as in [AcceptOptions].
	MaxMessageSize       int
	ReadTimeout          time.Duration
	WriteTimeout         time.Duration
	CompressionMode      CompressionMode
	CompressionThreshold int
}

DialOptions configures Dial. The zero value is valid.

type MessageType

type MessageType int

MessageType is the type of a data message.

const (
	MessageText   MessageType = 1
	MessageBinary MessageType = 2
)

Data message types. A text message must be valid UTF-8; received ones are checked, sent ones are not.

type StatusCode

type StatusCode int

StatusCode is a close status code (RFC 6455 section 7.4).

const (
	StatusNormalClosure           StatusCode = 1000
	StatusGoingAway               StatusCode = 1001
	StatusProtocolError           StatusCode = 1002
	StatusUnsupportedData         StatusCode = 1003
	StatusNoStatusReceived        StatusCode = 1005
	StatusAbnormalClosure         StatusCode = 1006
	StatusInvalidFramePayloadData StatusCode = 1007
	StatusPolicyViolation         StatusCode = 1008
	StatusMessageTooBig           StatusCode = 1009
	StatusMandatoryExtension      StatusCode = 1010
	StatusInternalError           StatusCode = 1011
	StatusServiceRestart          StatusCode = 1012
	StatusTryAgainLater           StatusCode = 1013
	StatusBadGateway              StatusCode = 1014
	StatusTLSHandshake            StatusCode = 1015
)

Close status codes. StatusNoStatusReceived, StatusAbnormalClosure and StatusTLSHandshake never appear in a Close frame and Conn.Close rejects them; the first two are reported for a Close frame without a status and for a connection that ended without a Close frame.

func CloseStatus

func CloseStatus(err error) StatusCode

CloseStatus returns the status code of the CloseError err is or wraps, or -1 if there is none.

Jump to

Keyboard shortcuts

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