websocketutil

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 22 Imported by: ? 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

Index

Constants

View Source
const (
	// The purpose of the connection was fulfilled
	CloseNormal = 1000
	// The endpoint is going away, a server shutting down or a client leaving
	CloseGoingAway = 1001
	// The peer broke the protocol
	CloseProtocolError = 1002
	// The peer sent a kind of data the endpoint cannot accept
	CloseUnsupportedData = 1003
	// The close frame carried no code; never sent with a code on the wire
	CloseNoStatus = 1005
	// The connection ended without a close frame; never sent on the wire
	CloseAbnormal = 1006
	// A message carried data inconsistent with its type, such as text that is not UTF-8
	CloseInvalidPayload = 1007
	// A message broke the endpoint's policy
	ClosePolicyViolation = 1008
	// A message was too big to process
	CloseMessageTooBig = 1009
	// The server did not negotiate an extension the client requires
	CloseMandatoryExtension = 1010
	// The endpoint hit an unexpected condition
	CloseInternalError = 1011
	// The server is restarting
	CloseServiceRestart = 1012
	// The server is overloaded, the client should come back later
	CloseTryAgainLater = 1013
	// A gateway got an invalid response from the server behind it
	CloseBadGateway = 1014
	// The TLS handshake failed; never sent on the wire
	CloseTLSHandshake = 1015
)

Close codes of the RFC 6455 registry

View Source
const (
	// Limit on the opening handshake
	DefaultOpenTimeout = 30 * time.Second
	// Wait for the peer's close frame
	DefaultCloseTimeout = 10 * time.Second
	// Silence from the peer before a keepalive ping
	DefaultPingInterval = 20 * time.Second
	// Largest message accepted, in bytes
	DefaultMaxMessageSize = 4 << 20
)

Defaults the zero fields of Options take

Variables

View Source
var ErrCloseTimeout error = &timeoutError{msg: "websocket peer did not answer the close frame in time"}

Close frame the peer did not answer within the close timeout

View Source
var ErrInvalidURL = errors.New("invalid websocket URL")

URL Connect refuses before dialing: one that does not parse, has a scheme other than ws, wss, http or https, or names no host

View Source
var ErrInvalidUTF8 = errors.New("websocket text message is not valid UTF-8")

Text message whose payload is not UTF-8, after which the connection is closed with CloseInvalidPayload

View Source
var ErrKeepaliveTimeout error = &timeoutError{msg: "websocket peer did not answer a keepalive ping in time"}

Keepalive ping after which nothing came from the peer within the ping timeout, or that could not be written within it, after which the connection is closed with CloseInternalError

View Source
var ErrMessageTooBig = errors.New("websocket message exceeds the size limit")

Message over the size limit, after which the connection is closed with CloseMessageTooBig

Functions

func CloseCodeText

func CloseCodeText(code int) string

Short meaning of a close code, such as "normal closure" for 1000, "registered" for 3000 to 3999, "private use" for 4000 to 4999 and "unknown" otherwise

func IsCleanClose

func IsCleanClose(err error) bool

Whether err holds a *CloseError of a clean closing handshake, the end a read loop treats as a normal finish

func WrapDialError

func WrapDialError(resp *http.Response, err error) error

Error of a gorilla/websocket dial: a *HandshakeError carrying the response when the server refused the upgrade, any other error unchanged and nil for nil

Types

type CloseError

type CloseError struct {
	// Code of the peer's close frame, CloseNoStatus when that frame carried none, CloseAbnormal when no close frame arrived
	Code int
	// Reason text of the peer's close frame
	Reason string
	// Code of the close frame this side sent, zero when it sent none
	SentCode int
	// Reason text of the close frame this side sent
	SentReason string
	// Whether this side sent its close frame before the peer's arrived
	SentFirst bool
	// What ended the connection when no close frame arrived: a network error, io.ErrUnexpectedEOF, ErrMessageTooBig, ErrInvalidUTF8, ErrKeepaliveTimeout, ErrCloseTimeout, the context error that cut a close short, a protocol violation of the peer or a compressed message that does not decompress (a flate.CorruptInputError)
	Err error
}

End of a connection: the close frames the two sides exchanged and, when the closing handshake did not complete, what ended it

func (*CloseError) Clean

func (e *CloseError) Clean() bool

Whether both sides exchanged close frames with CloseNormal, CloseGoingAway or CloseNoStatus

func (*CloseError) Error

func (e *CloseError) Error() string

Frames sent and received in the order they went, then the cause, such as "websocket closed: received 1001 (going away) bye; then sent 1001 (going away)"

func (*CloseError) Received

func (e *CloseError) Received() bool

Whether the peer sent a close frame

func (*CloseError) Unwrap

func (e *CloseError) Unwrap() error

The cause of an end without the peer's close frame

type Conn

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

Client connection with a background reader, keepalive pings and writes safe for concurrent use

func Connect

func Connect(ctx context.Context, rawURL string, opts Options) (*Conn, error)

Opens a client connection to a ws, wss, http or https URL, user info in the URL sent as basic authorization; ctx bounds only the opening handshake, whose failure is ctx's own error, an ErrInvalidURL error, a *HandshakeError, an *OpenTimeoutError or a *ConnectError

func (*Conn) Close

func (c *Conn) Close() error

Runs the closing handshake with CloseNormal, waiting for the peer's close frame up to the close timeout; nil once the handshake completed, else the *CloseError of how the connection ended

func (*Conn) CloseWith

func (c *Conn) CloseWith(ctx context.Context, code int, reason string) error

Runs the closing handshake with the code and a reason cut to fit a control frame, waiting for the peer's close frame until the close timeout counted from the call runs out or ctx ends, then drops the connection; nil once the handshake completed, else the *CloseError of how the connection ended

func (*Conn) Closed

func (c *Conn) Closed() bool

Whether this side has closed the connection or Receive has reported its end

func (*Conn) Done

func (c *Conn) Done() <-chan struct{}

Channel closed once the connection has ended and its network connection is gone

func (*Conn) Ping

func (c *Conn) Ping() error

Sends one ping frame without waiting for its pong, the *CloseError of the connection once it is closing or closed; a ping that cannot be written within the control frame wait fails the connection

func (*Conn) Receive

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

Next text or binary message; ctx's error when ctx ends the wait, the connection staying usable, and once the connection has ended its *CloseError, the messages that arrived before it delivered first

func (*Conn) SendBinary

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

Sends one binary message, the *CloseError of the connection once it is closing or closed

func (*Conn) SendText

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

Sends one text message, the *CloseError of the connection once it is closing or closed

func (*Conn) Subprotocol

func (c *Conn) Subprotocol() string

The subprotocol the server chose, empty when it chose none

type ConnectError

type ConnectError struct {
	// URL being connected to, without its user info, query and fragment
	URL string
	Err error
}

Connection attempt that failed before the server answered the upgrade: the name lookup, the dial, the proxy, the TLS handshake or the exchange of the upgrade itself

func (*ConnectError) Error

func (e *ConnectError) Error() string

The URL and the cause, such as "websocket connect to wss://example.com/ws: dial tcp 192.0.2.1:443: connect: connection refused"

func (*ConnectError) Unwrap

func (e *ConnectError) Unwrap() error

The cause

type HandshakeError

type HandshakeError struct {
	// HTTP status of the response, 101 when the server switched protocols but the handshake was invalid
	StatusCode int
	// Status line text such as "403 Forbidden", the standard text of the code when empty
	Status string
	// Response headers
	Header http.Header
	// Start of the response body, at most 1024 bytes
	Body []byte
	// URL the upgrade went to, without its user info, query and fragment
	URL string
	// What was wrong with the response: websocket.ErrBadHandshake, the compression the server negotiated or the subprotocol it chose; websocket.ErrBadHandshake when nil
	Err error
}

Upgrade request the server refused, or answered with a handshake that does not check out

func (*HandshakeError) Error

func (e *HandshakeError) Error() string

The URL and the status the server refused with, such as "websocket upgrade to wss://example.com/ws refused: 403 Forbidden"

func (*HandshakeError) Is

func (e *HandshakeError) Is(target error) bool

Whether target is websocket.ErrBadHandshake, which every handshake error matches whatever its precise cause

func (*HandshakeError) Unwrap

func (e *HandshakeError) Unwrap() error

What was wrong with the response, websocket.ErrBadHandshake unless a more precise cause is known

type Message

type Message struct {
	Type MessageType
	// Payload, valid UTF-8 for a Text message
	Data []byte
}

One data message received from the peer

type MessageType

type MessageType int

Kind of a data message, numbered as its WebSocket opcode

const (
	// UTF-8 text
	Text MessageType = websocket.TextMessage
	// Arbitrary bytes
	Binary MessageType = websocket.BinaryMessage
)

Data message kinds

func (MessageType) String

func (t MessageType) String() string

"text" or "binary", "opcode N" for any other value

type OpenTimeoutError

type OpenTimeoutError struct {
	// URL the handshake went to, without its user info, query and fragment
	URL string
	// Open timeout that ran out, zero when the operating system or a name server timed out first
	Limit time.Duration
	// Timeout the operating system or a name server reported, nil when the open timeout ran out
	Err error
}

Opening handshake that outlasted the open timeout, or whose dial or name lookup timed out first

func (*OpenTimeoutError) Error

func (e *OpenTimeoutError) Error() string

The URL and the limit or the cause, such as "websocket opening handshake with wss://example.com/ws timed out after 30s"

func (*OpenTimeoutError) Is

func (e *OpenTimeoutError) Is(target error) bool

Whether target is context.DeadlineExceeded or os.ErrDeadlineExceeded, the deadline errors the open timeout stands for

func (*OpenTimeoutError) Temporary

func (e *OpenTimeoutError) Temporary() bool

Always true: the same handshake may succeed when tried again

func (*OpenTimeoutError) Timeout

func (e *OpenTimeoutError) Timeout() bool

Always true: the error is a timeout

func (*OpenTimeoutError) Unwrap

func (e *OpenTimeoutError) Unwrap() error

The timeout the operating system or a name server reported, nil when the open timeout ran out

type Options

type Options struct {
	// Limit on the name lookup, dial, proxy, TLS handshake and upgrade together, DefaultOpenTimeout when zero, none besides the context when negative
	OpenTimeout time.Duration
	// Wait for the peer's close frame once this side sent its own, counted from the start of the close, DefaultCloseTimeout when zero, none at all when negative so a close drops the connection right after sending
	CloseTimeout time.Duration
	// Silence from the peer after which a keepalive ping goes out, DefaultPingInterval when zero, no keepalive pings when negative; time in which Receive is not taking messages and the reader waits does not count as silence
	PingInterval time.Duration
	// Wait for anything at all from the peer once a keepalive ping went out, and the limit on writing that ping, before the connection fails with CloseInternalError and ErrKeepaliveTimeout, the ping interval when zero or negative
	PingTimeout time.Duration
	// Limit on handing one whole message to the network, counted from the start of the send; none when zero or negative, the default, because a large message over a slow link can take any time; a send that runs out of it fails the connection, and without it a send held up by a peer that stops reading waits until the keepalive, the reader or Close ends the connection
	WriteTimeout time.Duration
	// Largest message accepted in bytes, counted after decompression, DefaultMaxMessageSize when zero, no limit when negative; a bigger one fails the connection with CloseMessageTooBig and ErrMessageTooBig
	MaxMessageSize int64
	// Extra headers of the upgrade request such as Origin, User-Agent, Authorization, Cookie or Sec-WebSocket-Protocol
	Header http.Header
	// Subprotocols offered in order of preference; a server choosing one offered neither here nor in a Sec-WebSocket-Protocol header fails the handshake, Conn.Subprotocol gives its choice
	Subprotocols []string
	// Proxy for the connection, nil to connect directly: httputil.Proxy follows the environment and then the operating system settings, http.ProxyURL pins one; http, https, socks5 and socks5h proxies work
	Proxy func(*http.Request) (*url.URL, error)
	// TLS settings of a wss connection, the defaults when nil; application protocols other than http/1.1 are dropped from it
	TLSConfig *tls.Config
	// Offer permessage-deflate compression without context takeover; a server that accepts it without granting client_no_context_takeover fails the handshake with a *HandshakeError of status 101, since gorilla/websocket cannot keep a compression context
	Compression bool
	// Wait before racing a dial over the other address family, net.Dialer.FallbackDelay: 300ms when zero, no racing when negative
	FallbackDelay time.Duration
}

Settings of one connection; a zero duration or size takes its default and a negative one switches the limit off, except WriteTimeout, which has no default

Jump to

Keyboard shortcuts

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