uws

package
v1.8.0 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2026 License: Apache-2.0 Imports: 26 Imported by: 2 modules, 1 package

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

Go Reference Autobahn License

uws is a WebSocket server and client for Go, built on the uio event engine. The handshake, frame parsing and your handler all run in the connection's own turn on a shared worker pool, so a connection costs no goroutine of its own, and a message that arrives in one frame reaches you straight from the read buffer.

Highlights

  • Standards first. RFC 6455 framing and close handshake, RFC 7692 permessage-deflate, and a clean run of the Autobahn test suite.
  • Three ways in. A native server that parses the upgrade itself, an http.Handler for existing net/http servers, and a client.
  • Zero-copy reads. Frames are unmasked in place, and an unfragmented, uncompressed message is handed to OnMessage straight from the read buffer.
  • Send from anywhere. SendText, SendBinary, Send and Ping are safe from any goroutine and keep their order; they never block on the socket.
  • Batched replies. Small replies to the frames of one read are encoded together and handed to the socket as one write.
  • Bounded by design. Limits on frame and message size; replies are paced by watermarks that pause the connection's reads instead of growing memory, and an optional hard limit refuses any send past it; handshake and close time are bounded, and heartbeats work on both ends.

Install

import "github.com/urpc/uio/uws"

The package ships inside the uio module; go get github.com/urpc/uio fetches it.

Quick start

package main

import (
	"log"

	"github.com/urpc/uio/uws"
)

type echo struct{}

func (echo) OnOpen(*uws.Conn)                  {}
func (echo) OnClose(*uws.Conn, uws.CloseEvent) {}

func (echo) OnMessage(c *uws.Conn, m uws.Message) {
	if m.Type == uws.TextMessage {
		_ = c.SendText(m.Text())
	} else {
		_ = c.SendBinary(m.Bytes())
	}
}

func main() {
	server := uws.NewServer(uws.Options{Handler: echo{}, EnableCompression: true})
	log.Fatal(server.Serve(":8080"))
}

Serve takes any number of addresses and returns once every connection has finished.

How it works

  1. Upgrade. Serve parses the HTTP upgrade natively; behind net/http the request is hijacked and the socket moved onto uio.
  2. Parse. Frames are unmasked in place. Text is validated as UTF-8, with a SIMD validator on amd64 with AVX2, and compressed messages are inflated.
  3. Handle. OnMessage runs in the connection's turn. The Handler callbacks of one connection are ordered and never overlap.
  4. Reply. What the handler sends is queued; small replies to one read's frames are batched into one write. Sends from other goroutines join the same queue in order. When a peer stops reading and the queue reaches the high watermark, the connection stops reading its socket until the queue drains.

Behind net/http

Server is also an http.Handler. Start its event loops with Serve() (no address), then mount it like any other handler:

server := uws.NewServer(uws.Options{Handler: echo{}})
go func() { log.Fatal(server.Serve()) }()

http.Handle("/ws", server)
log.Fatal(http.ListenAndServe(":8080", nil))

The handler takes over plain HTTP/1.1 connections. TLS and HTTP/2 connections cannot be moved onto uio's event loops: terminate TLS in a proxy in front, or let Serve take wss itself with TLSConfig. A request that arrives before Serve has started gets HTTP 500; Server.Ready closes a channel once the transport is up, so anything that mounts the handler programmatically — a proxy that builds it at start-up — can wait on it first.

Client

The callback form above suits one handler serving many connections. For a single connection used from one place, the pull form returns a ready client after the handshake:

client, err := uws.Dial(ctx, "ws://127.0.0.1:8080/")
if err != nil {
	log.Fatal(err)
}
defer client.Close(1000, "")

_ = client.SendText("hello")
for {
	message, err := client.ReadMessage(ctx)
	if err != nil {
		break // a *uws.CloseError once the queued messages ran out
	}
	log.Printf("%s", message.Payload)
}

uws.Dial uses uws.DefaultDialer, a default-options dialer that lives as long as the process. Dialer.DialClient is the same with a configured dialer, whose Options.Handler must be nil because the client owns the callbacks. A full message queue pauses the connection's reads — TCP flow control then slows the peer — so a client must either keep reading or be closed; Client.Close works either way. No message is dropped while the connection is open; one that arrives once this end has begun closing and finds the queue full is dropped rather than holding the close up. With a heartbeat configured, a client nobody reads keeps pinging and is closed once a Ping goes unanswered, its Pong stuck behind the unread messages. ReadMessage reports a *uws.CloseError after the connection ended and every message received before that was returned.

The callback form, for one handler serving every connection a dialer makes:

type client struct{}

func (client) OnOpen(c *uws.Conn)                  { _ = c.SendText("hello") }
func (client) OnMessage(c *uws.Conn, m uws.Message) { log.Printf("%s", m.Payload) }
func (client) OnClose(c *uws.Conn, e uws.CloseEvent) {
	if e.Err != nil {
		log.Println("closed:", e.Err)
	}
}

dialer := uws.NewDialer(uws.Options{Handler: client{}})
if err := dialer.Dial(ctx, "ws://127.0.0.1:8080/", nil); err != nil {
	log.Fatal(err)
}

Dial returns once the upgrade request is sent and the handshake finishes in the background; the connection reaches the application only through the handler. Its third argument is the connection's userdata, available as Conn.Userdata in every callback, so one stateless handler serves every dial. An error from Dial means no connection was made and no callback follows, uio.ErrFirstTurnRefused when a custom Executor declines the connection's first turn. After a nil error, OnOpen means the connection is ready, and OnClose always follows, with the cause in CloseEvent.Err; a failed handshake calls it without OnOpen. The context bounds the dial and the handshake, not the connection after it.

Configuration

Options holds every setting; Server and Dialer embed the same type and the zero value means the defaults, so the two ends cannot drift apart. Options are read when Serve or Dial first starts the transport and never again.

Field Default What it does
Subprotocols none Protocols to negotiate; a server prefers the order given.
MaxHeaderBytes 32 KiB Upgrade headers this end reads: the request on a server's native Serve path, the response on a dialer. Behind net/http, http.Server.MaxHeaderBytes applies instead.
MaxFramePayload 16 MiB Largest frame read; larger outgoing messages are fragmented.
MaxMessageSize 64 MiB Largest message, after decompression.
EnableCompression off Negotiates permessage-deflate.
CompressionLevel default flate level 1-9 when compression is on; there is no level 0.
KeepCompressionContext off Keeps this end's compression history between messages; off starts every message fresh and asks the same of the peer.
DisableUTF8Check off Skips text validation for trusted peers. Not RFC compliant.
HandshakeTimeout 10 s Bounds the HTTP upgrade.
CloseTimeout 5 s Bounds the close handshake.
HeartbeatInterval off Pings the peer at this interval; servers and dialers alike.
HeartbeatTimeout 2 × interval Closes the connection when a ping gets no pong in time.
Pollers uio default Event loops.
ReadBufferSize 4 KiB Bytes per socket read; it also sizes the write batch blocks (clamped to 4-64 KiB). Over TLS a record carries up to 16 KiB: a read smaller than that splits one record across several rounds, so a wss server moving bulk data reads about twice as fast with 16 KiB and half again with 64 KiB.
WriteCoalesce 4 KiB Writes smaller than this join the connection's outbound batch instead of taking a send of their own; a negative value turns size-based buffering off.
ReusePort off Sets SO_REUSEPORT on listeners.
Executor uio default Runs connection and write turns on the native backend; the stdio backend does not use it.
OutboundHighWatermark 64 KiB Queued output at which a connection stops reading, so TCP flow control slows its peer instead of the replies piling up. A negative value disables the pause.
OutboundLowWatermark High/4 Queued output at or below which a paused connection reads again.
MaxOutboundBuffered off Hard limit on one connection's queued output from any sender: a send past it returns ErrBackpressure and queues nothing. Size it to fit the largest message you send.

A Server adds CheckOrigin and Authorize, and a Dialer adds Header and RequestHeader (see Authentication). The Handler lives in Options, shared by every connection a server accepts or a dialer dials, with per-dial state passed as Dial's userdata. The underlying transport is built from these options and is not otherwise exposed; Executor is the scheduling escape hatch. Invalid combinations, such as a low watermark not below the high one, a high watermark above MaxOutboundBuffered, or a compression level outside 1-9, make Serve and Dial return ErrInvalidOptions.

Backpressure. The watermarks pace what a connection's own reads produce while its peer is slow. A connection whose queue reaches the high watermark stops consuming; the bytes pile up in the transport's inbound buffer until it stops reading the socket, and the peer's TCP window closes. Draining to the low watermark resumes reads; no message is dropped. Server.Stats and Dialer.Stats count the pauses and resumes.

Output that does not come from the connection's reads — a broadcast, a subscription push, any send from another goroutine — is not paced by the pause. Set MaxOutboundBuffered to bound it: past the limit SendText, SendBinary and Ping return ErrBackpressure, and the caller decides to drop, retry later or close.

Traffic metrics. A Handler that also implements TrafficObserver sees transport bytes in both directions. Both callbacks are observation only: do not call anything that sends or closes on the connection from them, and do not block. A report is the result of I/O that just happened, and a send from it feeds the report it answers; OnOutbound can also run while the write lock a send holds is held, so a send there deadlocks the connection. OnInbound runs in the connection's turn like the other callbacks; OnOutbound runs wherever a send completes and may overlap them, so keep what it touches safe for concurrent use:

func (m metrics) OnInbound(c *uws.Conn, n int)  { m.read.Add(n) }
func (m metrics) OnOutbound(c *uws.Conn, n int) { m.written.Add(n) }

Authentication

The upgrade request can carry credentials, and the server can refuse it before the WebSocket exists, so a rejected client costs no handshake and no callback:

dialer := &uws.Dialer{
	Header: http.Header{"Authorization": {"Bearer " + token}},
}

server := uws.NewServer(uws.Options{Handler: app{}})
server.Authorize = func(r *http.Request) (any, error) {
	user, err := verify(r.Header.Get("Authorization"))
	if err != nil {
		return nil, &uws.RejectError{Status: http.StatusUnauthorized, Reason: "bad token"}
	}
	return user, nil // the connection's Userdata from OnOpen on
}

Dialer.Header goes with every dial; Dialer.RequestHeader(userdata) adds per-dial headers on top. Headers the handshake sets itself are refused with ErrInvalidOptions: Host, Upgrade, Connection, Content-Length, Transfer-Encoding, Expect, and Sec-WebSocket-Key, -Version, -Protocol, -Extensions and -Accept. Authorize runs after the request passed validation and CheckOrigin, on the native path and behind net/http alike. A *RejectError answers with its status, header and reason; any other error with 403. The answer is sent before the connection closes, and the client gets it as a *HandshakeError — in CloseEvent.Err, or from DialClient through errors.As — carrying the status, the header and the reason. Without TLS the credentials travel in clear text: serve wss with TLSConfig, whose state Authorize sees on r.TLS — the server name asked for, a client certificate.

Secure WebSockets (wss)

Options.TLSConfig makes a server a wss one and lets a dialer speak wss:// — a crypto/tls configuration, run by uio/utls under the WebSocket protocol:

server := uws.NewServer(uws.Options{
	Handler:   handler,
	TLSConfig: &tls.Config{Certificates: certs},
})

dialer := uws.NewDialer(uws.Options{
	Handler:   handler,
	TLSConfig: &tls.Config{}, // system roots; each dial verifies its URL's host
})
err := dialer.Dial(ctx, "wss://example.org:443/socket", nil)

A dialer with a TLSConfig still dials ws:// in the clear; without one it refuses wss://. The TLS handshake runs before the WebSocket one, within HandshakeTimeout: one that fails fails the dial with its cause, and the Handler hears nothing of the connection. Behind net/http, ServeHTTP runs no TLS of its own and refuses a request that arrived over TLS: terminate TLS elsewhere and pass the plain HTTP/1.1 upgrade through, or let Serve take wss:// itself with a TLSConfig. A TLS record carries up to 16 KiB, so a ReadBufferSize of 16 KiB or more reads one record per syscall.

As a protocol layer

ServerLayer and ClientLayer run the WebSocket protocol as a uio.Layer, for stacks of your own — TLS, an obfuscation, a tunnel, in any order, on an uio.Events you configure:

listener, err := server.Listen(addr, uio.WithLayers(
	utls.Server(tlsConfig), uws.ServerLayer(uws.LayerOptions{Authorize: checkToken}), tunnel,
))
conn, err := client.DialContext(ctx, "tcp://example.org:443", uio.WithLayers(
	utls.Client(tlsConfig), uws.ClientLayer("wss://example.org/tunnel", uws.LayerOptions{}), tunnel,
))

The layer carries a byte stream: what the layer above writes leaves as Binary messages, and each message that arrives is handed up once whole, message boundaries dropped. It answers Pings, runs the heartbeat, answers a peer's Close, and sends one as the connection closes from above; a dial returns once the handshake succeeded, and reports a refusal as a *HandshakeError. The protocol's settings are Options' own; the transport's — Handler, Pollers, ReusePort, Executor, TLSConfig, MaxOutboundBuffered — belong to the Events, and options that name them fail every connection with ErrInvalidOptions (LayerOptions.Validate reports it up front). For messages, keep to Server and Dialer.

Rules of the road

  • Payloads are borrowed. Message.Payload is valid until OnMessage returns. Call Message.Clone to keep it or hand it to another goroutine. Message.Text and Message.Bytes hand the payload back to SendText and SendBinary without copying, for echoes.
  • Accepted is not delivered. A nil error from SendText, SendBinary or Ping means the message was queued in order, not that the peer has it. Replies to a peer that stops reading pause this connection's reads; sends from elsewhere are bounded only by MaxOutboundBuffered, past which they return ErrBackpressure.
  • State without locks. The Handler callbacks of one connection never overlap, so state kept with SetUserdata needs no locking from them; TrafficObserver.OnOutbound is the exception, and it must only observe — never send, close or block.
  • Closing. Conn.Close(code, reason) queues its close frame after everything already accepted and returns; the connection then completes the handshake with the peer, which CloseTimeout bounds. Protocol errors close with 1002, invalid UTF-8 with 1007, oversized messages with 1009.
  • Lifecycle. Server.Close and Dialer.Close request shutdown and return at once, so they are safe inside callbacks. A server or dialer cannot be restarted.

The API reference documents every type and method.

License

Apache License 2.0

The Go gopher in the banner is based on the original design by Renée French, licensed under CC BY 4.0.

Documentation

Overview

Package uws provides an asynchronous WebSocket server and client built on UIO.

Index

Constants

View Source
const (
	// DefaultMaxHeaderBytes is the default HTTP upgrade header limit.
	DefaultMaxHeaderBytes = handshake.DefaultMaxBytes
	// DefaultMaxFramePayload is the default wire payload limit for one frame.
	DefaultMaxFramePayload = 16 << 20
	// DefaultMaxMessageSize is the default decompressed message size limit.
	DefaultMaxMessageSize = 64 << 20
	// DefaultCloseTimeout is the default graceful close handshake timeout.
	DefaultCloseTimeout = 5 * time.Second
	// DefaultHandshakeTimeout is the default HTTP upgrade timeout.
	DefaultHandshakeTimeout = 10 * time.Second
)
View Source
const DefaultOutboundHighWatermark = 64 << 10

DefaultOutboundHighWatermark is the default queued-output level at which a connection stops reading its socket.

Variables

View Source
var (
	// ErrClosed reports an operation on a closed connection.
	ErrClosed = errors.New("uws: connection closed")
	// ErrNotReady reports an operation attempted before the handshake completes.
	ErrNotReady = errors.New("uws: handshake not complete")
	// ErrBackpressure reports a send MaxOutboundBuffered has no room for:
	// the queue is full, or the frame or message is larger than the limit
	// itself, which the queue's emptiness cannot fix.
	ErrBackpressure = errors.New("uws: outbound queue is full")
	// ErrServerStarted reports a second attempt to run a Server listener after
	// its transport has already started.
	ErrServerStarted = errors.New("uws: server already started")
	// ErrProtocol reports a WebSocket protocol violation.
	ErrProtocol = frame.ErrProtocol
)
View Source
var DefaultDialer = &Dialer{}

DefaultDialer is the Dialer the package-level Dial uses. It runs with the default options and lives until the process ends, like http.DefaultClient; close it and every connection it made by calling DefaultDialer.Close.

View Source
var ErrInvalidOptions = errors.New("uws: invalid options")

ErrInvalidOptions reports Options a server or dialer cannot run with.

Functions

func ClientLayer added in v1.8.0

func ClientLayer(target string, opts LayerOptions) uio.Layer

ClientLayer runs the client side of the WebSocket protocol as a uio.Layer: it sends the upgrade request for target, a ws:// or wss:// URL whose host and path the request names, and opens the layers above once the server accepted it. A dial through it returns once the handshake succeeded, and reports a refusal or a failure as its error — a *HandshakeError when the server answered. The scheme names no transport: TLS under the layer is another layer's, installed below it. One layer dials one target. See ServerLayer for the byte stream the layer carries and for invalid options.

func ServerLayer added in v1.8.0

func ServerLayer(opts LayerOptions) uio.Layer

ServerLayer runs the server side of the WebSocket protocol as a uio.Layer, for a stack of your own:

listener, err := events.Listen(addr,
	uio.WithLayers(tls, uws.ServerLayer(opts), tunnel))

It answers the upgrade request, and opens the layers above once the handshake succeeded; a request it refuses gets its answer and closes the connection — the layers above never see OnOpen, and end with OnClose alone. From then on it carries a byte stream: what the layer above writes leaves as Binary messages — split at MaxMessageSize — and the payload of every message that arrives, Text or Binary, is handed up once the message is whole, message boundaries dropped. Pings are answered, heartbeats run, and a Close from the peer is answered and ends the connection. Closing the connection from above sends a Close frame first: 1000 for a graceful close, 1011 for an abort — an abort sends it best-effort, since nothing is flushed or drained. The stream has no half-close: CloseWrite is not supported.

Each write from above leaves as its own frame, through the Events the layer runs on: set its WriteBufferedThreshold for the writes a Handler makes in one callback to leave in one send, as a Server's do.

Options that are not valid for a layer fail every connection through it with ErrInvalidOptions — a dial reports it — as LayerOptions.Validate does.

The layer above can read the negotiated subprotocol — and what Authorize returned for this connection — through uio.FindLayer:

if ws, ok := uio.FindLayer[interface{ Userdata() any }](conn); ok { … }
if ws, ok := uio.FindLayer[interface{ Subprotocol() string }](conn); ok { … }

Types

type Client added in v1.8.0

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

Client is a WebSocket client connection whose messages are read on demand: DialClient hands one over after the handshake, SendText and SendBinary write, and ReadMessage returns the next received message. The connection must be read continuously: a Client whose messages are not being read stops reading, so the peer's flow control slows it and its control frames, Ping included, go unanswered. Its own sends slow with it: one made while the queue is full waits for reading to resume before it leaves. Client.Close always ends a Client, however many messages are waiting, and so do the closes this end starts itself — Dialer.Close, a deadline, a heartbeat timeout, a failed send: a message that arrives once one has begun and finds the queue full is dropped rather than holding the close up.

func Dial added in v1.8.0

func Dial(ctx context.Context, addr string) (*Client, error)

Dial connects with DefaultDialer and returns the client once the handshake completes. See Dialer.DialClient for the contract.

func (*Client) Close added in v1.8.0

func (c *Client) Close(code uint16, reason string) error

Close closes the connection with code and reason. It also ends reading: messages still in the queue are returned by further ReadMessage calls until they run out, and an OnMessage stuck on a full queue gives up at once. An invalid code or reason returns the error with the connection untouched, still reading.

func (*Client) CloseEventInfo added in v1.8.0

func (c *Client) CloseEventInfo() CloseEvent

CloseEventInfo reports how the connection ended. It is meaningful once ReadMessage has returned a CloseError, or after Close returned and the connection finished closing.

func (*Client) ReadMessage added in v1.8.0

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

ReadMessage returns the next received message, waiting for ctx to allow one. It reports a *CloseError after the connection closed and every message that was received before that has been returned; a canceled or timed-out ctx returns its error with the connection unaffected.

type CloseError added in v1.8.0

type CloseError struct {
	CloseEvent
}

CloseError reports how a Client's connection ended. ReadMessage returns it after the connection closed and every queued message was returned.

func (*CloseError) Error added in v1.8.0

func (e *CloseError) Error() string

func (*CloseError) Unwrap added in v1.8.0

func (e *CloseError) Unwrap() error

Unwrap exposes the transport, protocol or application error in CloseEvent, so a deadline or cancellation that ended the dial still matches with errors.Is.

type CloseEvent added in v1.1.0

type CloseEvent struct {
	// Code is the peer or locally generated WebSocket close status code.
	Code uint16
	// Reason is the optional close reason sent with Code.
	Reason string
	// Err is the transport, protocol, or application error that caused closure.
	Err error
}

CloseEvent describes why a WebSocket connection closed.

type Conn

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

Conn is an established or handshaking WebSocket connection. UIO serializes protocol and handler callbacks per connection; atomics here coordinate external writers, timers, heartbeat scanning, and transport callbacks. The fields every message touches come first, so they share as few cache lines as the struct's size class allows.

func (*Conn) Close

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

Close starts a graceful WebSocket close handshake. The Close frame follows every message accepted before it. When the outbound limit has no room for the frame, it waits for the transport to drain instead of failing; either way the connection stops accepting messages, and one that arrives already received but not yet reported to the Handler is dropped rather than delivered. CloseTimeout bounds the handshake, which the connection carries on after Close returns.

func (*Conn) IsClosed

func (c *Conn) IsClosed() bool

IsClosed reports whether the connection has closed.

func (*Conn) LocalAddr

func (c *Conn) LocalAddr() net.Addr

LocalAddr returns the local transport address.

func (*Conn) Ping

func (c *Conn) Ping(payload []byte) error

Ping sends a ping control frame with up to 125 bytes of payload.

func (*Conn) RemoteAddr

func (c *Conn) RemoteAddr() net.Addr

RemoteAddr returns the peer transport address.

func (*Conn) Request added in v1.1.0

func (c *Conn) Request() *http.Request

Request returns the HTTP upgrade request during OnOpen for server connections, whether accepted by Server.Serve or adopted through Server.ServeHTTP. It returns nil afterward — handlers that need it beyond OnOpen must keep it — and for client connections. The request is read-only.

func (*Conn) Send added in v1.8.0

func (c *Conn) Send(typ MessageType, payload []byte) error

Send queues payload as one message of typ — TextMessage or BinaryMessage — framing it with that opcode. It is SendText and SendBinary under one name for a caller that holds bytes and a type already: text goes out without converting the bytes to a string first. An unknown typ reports ErrProtocol.

As with SendText and SendBinary, payload is framed without being retained: the bytes may be reused once Send returns. A text payload must be valid UTF-8; it is sent as given, and only received text is validated.

func (*Conn) SendBinary

func (c *Conn) SendBinary(payload []byte) error

SendBinary queues payload as one binary message. The transport flushes accepted data in the connection's current or next I/O task.

func (*Conn) SendText

func (c *Conn) SendText(payload string) error

SendText queues payload as one text message. The transport flushes accepted data in the connection's current or next I/O task. payload must be valid UTF-8: it is sent as given, and only received text is validated.

payload's bytes are framed without a copy: a string converts to the transaction's view of the wire for free, and nothing on the send path writes through it.

func (*Conn) SetDeadline added in v1.1.0

func (c *Conn) SetDeadline(deadline time.Time) error

SetDeadline forwards the transport read and write deadline. A zero value clears it.

func (*Conn) SetNoDelay added in v1.1.0

func (c *Conn) SetNoDelay(noDelay bool) error

SetNoDelay controls whether the underlying TCP connection uses Nagle's algorithm.

func (*Conn) SetReadDeadline added in v1.1.0

func (c *Conn) SetReadDeadline(deadline time.Time) error

SetReadDeadline forwards the transport read deadline. A zero value clears it.

func (*Conn) SetUserdata added in v1.1.0

func (c *Conn) SetUserdata(value any)

SetUserdata replaces the user data associated with the connection. It is not safe for concurrent use from multiple goroutines.

func (*Conn) SetWriteDeadline added in v1.1.0

func (c *Conn) SetWriteDeadline(deadline time.Time) error

SetWriteDeadline forwards the transport write deadline. A zero value clears it.

func (*Conn) Subprotocol

func (c *Conn) Subprotocol() string

Subprotocol returns the negotiated WebSocket subprotocol, or an empty string.

func (*Conn) TLSState added in v1.8.0

func (c *Conn) TLSState() (tls.ConnectionState, bool)

TLSState reports the TLS connection state of a connection that runs over TLS — a wss one, or one whose stack has a TLS layer below the WebSocket protocol: what the handshake settled on, the server name the client asked for, the client's certificates.

func (*Conn) Userdata added in v1.1.0

func (c *Conn) Userdata() any

Userdata returns the user data associated with the connection. It is not safe for concurrent use from multiple goroutines.

type Dialer

type Dialer struct {
	// Options configures the protocol, the transport and backpressure.
	Options
	// Header is added to every upgrade request, for credentials such as an
	// Authorization token. The headers the handshake sets itself are refused
	// — Host, Upgrade, Connection, Content-Length, Transfer-Encoding, Expect,
	// and Sec-WebSocket-Key, -Version, -Protocol, -Extensions and -Accept —
	// the first Dial returns ErrInvalidOptions.
	Header http.Header
	// RequestHeader, when set, returns headers for one dial, given its
	// userdata — nil for a DialClient, which dials without one; they replace
	// Header's values of the same name. A header the handshake sets itself
	// fails that Dial with ErrInvalidOptions.
	RequestHeader func(userdata any) http.Header
	// contains filtered or unexported fields
}

Dialer creates outbound WebSocket connections over a shared UIO transport. Configure its fields before the first Dial; the first Dial freezes the connection configuration.

func NewDialer

func NewDialer(opts Options) *Dialer

NewDialer returns a Dialer using opts.

func (*Dialer) Close

func (d *Dialer) Close(err error) error

Close permanently stops the dialer, cancels in-flight connection attempts, and requests closure of established connections. Subsequent Dial calls return the first close cause. OnClose reports connection completion.

func (*Dialer) Dial

func (d *Dialer) Dial(ctx context.Context, addr string, userdata any) error

Dial starts a WebSocket connection and returns once the upgrade request is on its way — with a TLSConfig, once the transport's stack opened, which is where the request is written from; the Handler reports the rest. An error means no connection was made and no callback follows — uio.ErrFirstTurnRefused when a custom Executor declined the connection's first turn. After a nil error, OnOpen reports a completed handshake, and OnClose always reports how the connection ended, a failed handshake or upgrade request included. userdata is the connection's Userdata in every callback. ctx bounds the TCP connection and the handshake, not the connection after OnOpen.

func (*Dialer) DialClient added in v1.8.0

func (d *Dialer) DialClient(ctx context.Context, addr string) (*Client, error)

DialClient connects and returns the client once the handshake completes, ready to send and read: the pull-mode counterpart of Dial, which reports connection events to Options.Handler instead. The dialer's Handler must be nil, since the client takes the callbacks; DialClient returns ErrInvalidOptions otherwise. ctx bounds the TCP connection and the handshake, not the connection after it.

func (*Dialer) Stats added in v1.8.0

func (d *Dialer) Stats() Stats

Stats reports the read pausing of this dialer's connections.

type Handler

type Handler interface {
	// OnOpen is called after a successful WebSocket handshake.
	OnOpen(*Conn)
	// OnMessage receives complete messages in wire order.
	OnMessage(*Conn, Message)
	// OnClose is called once after the transport closes. A client handshake
	// failure may call it without a preceding OnOpen.
	OnClose(*Conn, CloseEvent)
}

Handler receives ordered lifecycle and message callbacks for a connection.

type HandshakeError added in v1.8.0

type HandshakeError struct {
	StatusCode int
	Header     http.Header
	// Reason is the response body, when the server sent a short one; a uws
	// server sends RejectError.Reason there.
	Reason string
}

HandshakeError reports a server that refused the upgrade: it answered with a status other than 101. A Dialer's OnClose gets it as CloseEvent.Err, and DialClient returns it, wrapped in a CloseError, so errors.As finds it.

func (*HandshakeError) Error added in v1.8.0

func (e *HandshakeError) Error() string

type LayerOptions added in v1.8.0

type LayerOptions struct {
	// Options holds the protocol's settings: subprotocols, limits,
	// compression, timeouts, heartbeats and the outbound watermarks;
	// ReadBufferSize and WriteCoalesce size only the layer's write batches
	// and read rounds, as the socket's reads are its Events'. The transport's
	// own — Handler, Pollers, ReusePort, Executor, TLSConfig and
	// MaxOutboundBuffered — belong to the Events the layer is installed on
	// and must be left zero: a stack's TLS is a layer of its own, and its
	// outbound limit is the Events' MaxOutboundBuffered.
	Options
	// CheckOrigin and Authorize decide a ServerLayer's upgrade requests as
	// they do a Server's; what Authorize returns is the layer's to report,
	// through uio.FindLayer — see ServerLayer.
	CheckOrigin func(*http.Request) bool
	Authorize   func(r *http.Request) (userdata any, err error)
	// Header is added to a ClientLayer's upgrade request, as a Dialer's is.
	Header http.Header
}

LayerOptions configures ServerLayer and ClientLayer.

func (LayerOptions) Validate added in v1.8.0

func (o LayerOptions) Validate(target string) error

Validate reports what ServerLayer, and ClientLayer for target when it is not empty, would refuse: the error every connection through the layer would fail with.

type Message

type Message struct {
	// Type identifies whether Payload contains text or binary data.
	Type MessageType
	// Payload is valid until OnMessage returns. Call Clone before retaining it
	// or handing it to another goroutine.
	Payload []byte
}

Message is one complete text or binary WebSocket message.

func (Message) Bytes added in v1.8.0

func (m Message) Bytes() []byte

Bytes returns Payload, the counterpart of Text for a binary message handed straight back to SendBinary. It is Payload itself, valid on the same terms: only until OnMessage returns unless cloned.

func (Message) Clone

func (m Message) Clone() Message

Clone returns an independently owned copy of m.

func (Message) Text added in v1.8.0

func (m Message) Text() string

Text returns Payload as a string without copying, for the common echo — handing a text message straight back to SendText. Like Payload, it is valid only until OnMessage returns; call Clone to keep either past it.

type MessageType

type MessageType uint8

MessageType identifies the payload format of a WebSocket message.

const (
	// TextMessage identifies a UTF-8 text message.
	TextMessage MessageType = 1
	// BinaryMessage identifies a binary message.
	BinaryMessage MessageType = 2
)

type Options added in v1.8.0

type Options struct {
	// Handler receives the connection callbacks of every connection the
	// server or dialer makes. It may be nil, which leaves the protocol
	// running without application callbacks; a Dialer whose Handler is set
	// refuses DialClient, which installs its own.
	Handler Handler
	// Subprotocols lists supported protocols in server preference order,
	// offered in the same order by a Dialer.
	Subprotocols []string

	// MaxHeaderBytes bounds the HTTP upgrade headers this end reads: the
	// request on a server, the response on a dialer. Zero uses 32 KiB.
	MaxHeaderBytes int
	// MaxFramePayload bounds each wire frame payload. On reads, it also
	// bounds aggregate compressed payload across a fragmented message. Zero
	// uses 16 MiB.
	MaxFramePayload uint64
	// MaxMessageSize bounds a complete message after decompression. Zero uses
	// 64 MiB.
	MaxMessageSize uint64

	// EnableCompression enables RFC 7692 permessage-deflate.
	EnableCompression bool
	// CompressionLevel selects the flate level, 1 through 9. Zero uses the
	// library default level; there is no level 0: permessage-deflate with no
	// compression only adds framing overhead.
	CompressionLevel int
	// KeepCompressionContext keeps this end's compression context between
	// messages. Off by default: every message starts a fresh context and the
	// negotiation asks for the same of the peer, which bounds per-connection
	// compression state.
	KeepCompressionContext bool
	// DisableUTF8Check skips Text message UTF-8 validation. This violates RFC
	// 6455 and should only be used with trusted peers. Close reasons remain
	// validated.
	DisableUTF8Check bool

	// HandshakeTimeout bounds the HTTP upgrade handshake. Zero uses 10s.
	HandshakeTimeout time.Duration
	// CloseTimeout bounds the graceful WebSocket close handshake. Zero uses
	// 5s.
	CloseTimeout time.Duration

	// HeartbeatInterval makes this end ping its peer when positive. Zero
	// disables heartbeats; both servers and dialers may enable them. The
	// heartbeat runs in the connection's own turns, so a Handler callback
	// that blocks also pauses its connection's heartbeat until it returns;
	// a Client waiting on its full queue is bounded so its timeout still runs.
	HeartbeatInterval time.Duration
	// HeartbeatTimeout bounds both the time a ping may remain queued and the
	// time to receive its matching pong after it is written. Zero uses twice
	// HeartbeatInterval.
	HeartbeatTimeout time.Duration

	// Pollers is the number of event loops. Zero uses UIO's default.
	Pollers int
	// ReadBufferSize is the size of each socket read. Zero uses UIO's default
	// of 4 KiB. It also sizes the write batch blocks the connection's replies
	// are coalesced into, clamped to 4-64 KiB. With TLSConfig a record
	// carries up to 16 KiB and a read smaller than that splits one record
	// across several rounds; a wss server moving bulk data reads about twice
	// as fast with 16 KiB and half again with 64 KiB.
	ReadBufferSize int
	// WriteCoalesce makes callback writes smaller than this value join the
	// connection's outbound batch instead of attempting an immediate send.
	// Zero uses 4 KiB; a negative value disables size-based buffering.
	WriteCoalesce int
	// ReusePort sets SO_REUSEPORT on listeners.
	ReusePort bool
	// Executor runs the connection and write turns; nil uses UIO's own
	// scheduler.
	Executor uio.Executor

	// TLSConfig makes the connections wss. On a Server it holds the
	// certificates, and every connection the Server accepts runs TLS under
	// the WebSocket protocol; ServeHTTP still takes plain HTTP/1.1 upgrades
	// only. Authorize sees the TLS state on its request's TLS field, and
	// Conn.TLSState reports it. On a Dialer it is what wss:// dials verify
	// the server with — an empty Config verifies against the system roots —
	// and when it names no ServerName, each dial verifies the host its URL
	// names; ws:// dials run without TLS. A Dialer without it refuses wss://.
	// The TLS handshake runs before the WebSocket one, each bounded by
	// HandshakeTimeout, and a dial that fails it reports its cause.
	TLSConfig *tls.Config
	// OutboundHighWatermark is the queued output at which a connection stops
	// reading its socket, so TCP flow control slows its peer instead of the
	// replies to its requests piling up. It paces only what the connection's
	// own reads produce; output sent from elsewhere, such as a broadcast, is
	// bounded by MaxOutboundBuffered. A negative value disables the pause.
	// Zero uses 64 KiB.
	OutboundHighWatermark int
	// OutboundLowWatermark is the queued level at or below which a paused
	// connection reads again. Zero uses a quarter of the high watermark.
	OutboundLowWatermark int
	// MaxOutboundBuffered bounds the bytes queued for one connection from any
	// sender: a send that would pass it returns ErrBackpressure and queues
	// nothing, so a slow peer cannot grow the queue without bound however the
	// output is produced. Size it to fit the largest message sent. Zero means
	// no limit.
	MaxOutboundBuffered int
}

Options holds every setting a Server or Dialer accepts. The zero value means the defaults; the fields are documented with them. Server and Dialer share the type so the two ends cannot drift apart. A value is read when Serve or Dial first starts its transport and never again: changing the Options of a running Server or Dialer has no effect.

type RejectError added in v1.8.0

type RejectError struct {
	Status int
	Header http.Header
	Reason string
}

RejectError is what Server.Authorize returns to refuse an upgrade with a response of its choosing. Status is the HTTP status, 403 when zero or not a 4xx or 5xx code; Header is added to the response — all of it or none: one reserved or malformed name drops the whole header; Reason is its plain-text body, cut to 4 KiB on a whole character, which a uws client reports as HandshakeError.Reason.

func (*RejectError) Error added in v1.8.0

func (e *RejectError) Error() string

type Server

type Server struct {
	// Options configures the protocol, the transport and backpressure, and
	// carries the Handler every connection reports to.
	Options
	// CheckOrigin accepts an upgrade request. Nil accepts every origin.
	CheckOrigin func(*http.Request) bool
	// Authorize decides an upgrade request that passed validation and
	// CheckOrigin, before the server answers it. A nil error accepts it, and
	// userdata becomes the connection's Userdata from OnOpen on (`uws.Conn`
	// in the sugar; a stack's `ServerLayer` reports it through
	// uio.FindLayer instead). On the ServeHTTP path Authorize runs on the
	// http server's goroutine, before the connection is adopted. An error
	// refuses it: a *RejectError with the status, header and reason it names,
	// any other error with 403. A refused connection never reaches the
	// Handler. Authorize runs on the connection's turn, so a slow check holds
	// up that connection only; it must not block for long all the same. Nil
	// accepts every request.
	Authorize func(r *http.Request) (userdata any, err error)
	// contains filtered or unexported fields
}

Server accepts WebSocket connections over a UIO transport. Configure its fields before calling Serve; Serve freezes the connection configuration.

func NewServer

func NewServer(opts Options) *Server

NewServer returns a Server using opts. http.Server-style: the exported fields are the configuration, this constructor only fills them in.

func (*Server) Close

func (s *Server) Close(err error) error

Close permanently stops the server and requests transport shutdown. It returns once the shutdown is requested; a Serve running on the server returns after all event loops and connection tasks have exited.

func (*Server) Ready added in v1.8.0

func (s *Server) Ready() <-chan struct{}

Ready returns a channel closed once Serve has brought the transport up: the moment ServeHTTP begins accepting upgrades. A Server that never gets there — Serve failed to bind, or Close came first — never closes it, so a caller waiting on it must bound the wait. Mounting behind net/http, wait on this before taking traffic: an upgrade that arrives earlier gets HTTP 500.

func (*Server) Serve

func (s *Server) Serve(addrs ...string) error

Serve starts the event loops and listens on each supplied address. Calling Serve without an address prepares the Server for use as an http.Handler.

func (*Server) ServeHTTP added in v1.1.0

func (s *Server) ServeHTTP(writer http.ResponseWriter, request *http.Request)

ServeHTTP upgrades a plain HTTP/1.1 TCP connection and transfers it from net/http to the Server's UIO event loops. Serve must already be running. TLS and HTTP/2 are not supported.

func (*Server) Stats added in v1.8.0

func (s *Server) Stats() Stats

Stats reports the read pausing of this server's connections.

type Stats added in v1.8.0

type Stats struct {
	ReadsPaused  uint64
	ReadsResumed uint64
}

Stats reports per-connection read pausing, the effect of OutboundHighWatermark: a pause means the peer is not keeping up with its replies.

type TrafficObserver added in v1.8.0

type TrafficObserver interface {
	OnInbound(*Conn, int)
	OnOutbound(*Conn, int)
}

TrafficObserver reports transport traffic. Implement it on the Handler to receive both directions of every connection.

Both callbacks are observation only. They must not call any method that sends or closes on the connection (SendText, SendBinary, Ping, Close, ...): a report is the result of I/O that just happened, and writing from it feeds the report it answers — it retires more bytes, which reports again. In uws the report can also run while the write lock a send holds is still held, so a write here deadlocks the connection. They must not block either.

OnInbound runs in the connection's turn and never overlaps its Handler callbacks. OnOutbound runs wherever the transport finishes a send — a write turn, a writer goroutine, or the goroutine closing the connection, possibly with internal locks held — and may overlap the connection's Handler callbacks and OnInbound, so state it shares with them must be safe for concurrent use.

Directories

Path Synopsis
autobahn
server command
examples
echo command
nethttp command
internal
compress
Package compress implements RFC 7692 message DEFLATE with bounded output and negotiated context takeover.
Package compress implements RFC 7692 message DEFLATE with bounded output and negotiated context takeover.
extension
Package extension parses and negotiates WebSocket extension headers.
Package extension parses and negotiates WebSocket extension headers.
frame
Package frame implements the wire-level WebSocket frame codec.
Package frame implements the wire-level WebSocket frame codec.
handshake
Package handshake parses, validates, and builds RFC 6455 HTTP upgrades.
Package handshake parses, validates, and builds RFC 6455 HTTP upgrades.

Jump to

Keyboard shortcuts

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