ws

package
v0.0.0-...-df8f258 Latest Latest
Warning

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

Go to latest
Published: Jun 11, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package ws provides WebSocket connection utilities including reading, writing, and lifecycle management.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsErrWebsocketAlreadyClosed

func IsErrWebsocketAlreadyClosed(err error) bool

IsErrWebsocketAlreadyClosed reports whether err indicates the websocket was already closed.

func IsErrWebsocketClosed

func IsErrWebsocketClosed(err error) bool

IsErrWebsocketClosed reports whether err indicates the websocket was closed.

func LogWebsocketReadError

func LogWebsocketReadError(ctx context.Context, err error)

LogWebsocketReadError logs a websocket read error using the context logger.

func LogWebsocketWriteError

func LogWebsocketWriteError(ctx context.Context, targetName string, err error)

LogWebsocketWriteError logs a websocket write error for the given target using the context logger.

Types

type AcceptOption

type AcceptOption func(*acceptConfig) error

AcceptOption configures the Accept call.

func WithAcceptBufferPoolOpt

func WithAcceptBufferPoolOpt(bufferPool BufferPool) AcceptOption

WithAcceptBufferPoolOpt sets the buffer pool for the accepted connection.

func WithAcceptCompressionThreshold

func WithAcceptCompressionThreshold(enabled bool) AcceptOption

WithAcceptCompressionThreshold sets whether compression should be negotiated.

func WithAcceptSubprotocols

func WithAcceptSubprotocols(subprotocols ...string) AcceptOption

WithAcceptSubprotocols sets the subprotocols for the WebSocket handshake.

type BufferPool

type BufferPool interface {
	Get() *bytes.Buffer
	Put(buf *bytes.Buffer)
}

BufferPool is an interface for getting and putting *bytes.Buffer instances.

type CloseError

type CloseError = websocket.CloseError

CloseError represents a WebSocket close frame with a status code and text.

func GetWebsocketCloseError

func GetWebsocketCloseError(err error) *CloseError

GetWebsocketCloseError extracts a CloseError from err, or returns nil if none is present.

type Conn

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

Conn is a wrapper around a *websocket.Conn that provides a background writer, and use of a buffer pool for temporary buffers.

func Accept

func Accept(w http.ResponseWriter, r *http.Request, opts ...AcceptOption) (*Conn, error)

Accept accepts a WebSocket handshake from a client and returns a Conn.

func Dial

func Dial(ctx context.Context, u string, opts ...DialOption) (*Conn, *http.Response, error)

Dial dials a WebSocket connection and returns a Conn. Context is only used for the actual Dial, so one can provide a timeout. Later, one must call Close() to close the connection and clean up resources.

func NewConn

func NewConn(conn *websocket.Conn, opts ...ConnOption) *Conn

NewConn creates a new Conn wrapper around a *websocket.Conn.

func (*Conn) AsyncWriter

func (w *Conn) AsyncWriter(ctx context.Context, messageType MessageType) (io.WriteCloser, error)

AsyncWriter returns a writer for the given message type. The closing of the writer will send the written data via a background goroutine, not waiting for the write to complete before returning from Close().

func (*Conn) Close

func (w *Conn) Close(code StatusCode, reason string) error

Close closes the WebSocket connection with the given status code and reason.

func (*Conn) Flush

func (w *Conn) Flush(ctx context.Context) error

Flush waits for all pending write messages (at the time Flush is called) to complete. The websocket may continue to be used unless it has been closed.

func (*Conn) GetStats

func (w *Conn) GetStats() ConnStats

GetStats returns a snapshot of the connection statistics.

func (*Conn) Ping

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

Ping sends a ping frame and waits for a pong frame.

func (*Conn) ReadJSON

func (w *Conn) ReadJSON(ctx context.Context, v any) error

ReadJSON reads a JSON message from the WebSocket connection and unmarshals it into v You can only have 2 concurrent reader at any given time, including combined with Reader().

func (*Conn) Reader

func (w *Conn) Reader(ctx context.Context) (Reader, error)

Reader returns the message type, an io.ReadCloser that can be used to read the message. The returned reader should be closed after use to return the buffer to the pool. You can only have 1 concurrent reader at any given time, including combined with ReadJSON().

func (*Conn) SetReadDeadline

func (w *Conn) SetReadDeadline(t time.Time) error

SetReadDeadline sets the read deadline on the underlying connection. Setting a deadline in the past unblocks a pending Reader() call.

func (*Conn) SetReadLimit

func (w *Conn) SetReadLimit(n int64)

SetReadLimit sets the maximum size of incoming messages.

func (*Conn) Subprotocol

func (w *Conn) Subprotocol() string

Subprotocol returns the negotiated subprotocol.

func (*Conn) Write

func (w *Conn) Write(ctx context.Context, messageType MessageType, data []byte) error

Write writes a message to the WebSocket connection via a background goroutine, waiting for the context to be cancelled, or for the write to complete or error.

func (*Conn) WriteAsync

func (w *Conn) WriteAsync(ctx context.Context, messageType MessageType, data []byte) error

WriteAsync writes a message asynchronously via a background goroutine.

func (*Conn) WriteAsyncFromReader

func (w *Conn) WriteAsyncFromReader(ctx context.Context, reader Reader) error

WriteAsyncFromReader writes data from a Reader asynchronously via a background goroutine.

func (*Conn) WriteFromReader

func (w *Conn) WriteFromReader(ctx context.Context, reader Reader) error

WriteFromReader writes data from a Reader asynchronously via a background goroutine, waiting for the context to be cancelled, or the write to complete or error.

func (*Conn) WriteJSON

func (w *Conn) WriteJSON(ctx context.Context, v any) error

WriteJSON marshals v to JSON and writes it to the WebSocket connection via a background goroutine, waiting for the context to be cancelled, or the write to complete or error.

func (*Conn) WriteJSONAsync

func (w *Conn) WriteJSONAsync(ctx context.Context, obj any) error

WriteJSONAsync marshals obj to JSON using buffer_pool and writes it asynchronously via a background goroutine.

func (*Conn) Writer

func (w *Conn) Writer(ctx context.Context, messageType MessageType) (io.WriteCloser, error)

Writer returns a writer for the given message type. The closing of the writer will send the written data via a background goroutine, waiting for the context to be cancelled, or for the write to complete or error.

type ConnOption

type ConnOption func(*Conn)

ConnOption is a functional option for NewConn.

func WithBufferPoolOpt

func WithBufferPoolOpt(bufferPool BufferPool) ConnOption

WithBufferPoolOpt returns a ConnOption that sets the buffer pool.

func WithConnectedAtOpt

func WithConnectedAtOpt(t time.Time) ConnOption

WithConnectedAtOpt allows setting the time the connection started vs the default of 'now'. A zero time.Time also means 'now'.

type ConnStats

type ConnStats struct {
	ConnectedAt time.Time

	LastReceivedAt   time.Time
	MessagesReceived int64
	BytesReceived    int64

	LastSentAt   time.Time
	MessagesSent int64
	BytesSent    int64
}

ConnStats tracks connection statistics including message counts and timestamps.

func (*ConnStats) Add

func (st *ConnStats) Add(other ConnStats)

Add merges another ConnStats into this one.

func (*ConnStats) LastSeenAt

func (st *ConnStats) LastSeenAt() time.Time

LastSeenAt returns the most recent activity timestamp for this connection.

type DialOption

type DialOption func(*dialConfig) error

DialOption configures the Dial call.

func WithDialBufferPoolOpt

func WithDialBufferPoolOpt(bufferPool BufferPool) DialOption

WithDialBufferPoolOpt sets the buffer pool for the dialed connection.

func WithDialCompression

func WithDialCompression(enabled bool) DialOption

WithDialCompression sets whether compression should be negotiated.

func WithDialHTTPHeader

func WithDialHTTPHeader(header http.Header) DialOption

WithDialHTTPHeader sets the HTTP headers for the WebSocket dial.

func WithDialSubprotocols

func WithDialSubprotocols(subprotocols ...string) DialOption

WithDialSubprotocols sets the subprotocols for the WebSocket dial.

type MessageType

type MessageType = int

MessageType constants to match fasthttp websocket API.

const (
	MessageText   MessageType = websocket.TextMessage
	MessageBinary MessageType = websocket.BinaryMessage
)

WebSocket message type constants.

type Reader

type Reader interface {
	io.Reader
	Bytes() []byte
	MessageType() MessageType
	Len() int
	Done()
}

Reader is the interface for reading WebSocket messages.

type StatusCode

type StatusCode = int

StatusCode constants to match coder websocket API.

const (
	StatusNormalClosure           StatusCode = websocket.CloseNormalClosure
	StatusGoingAway               StatusCode = websocket.CloseGoingAway
	StatusProtocolError           StatusCode = websocket.CloseProtocolError
	StatusUnsupportedData         StatusCode = websocket.CloseUnsupportedData
	StatusNoStatusRcvd            StatusCode = websocket.CloseNoStatusReceived
	StatusAbnormalClosure         StatusCode = websocket.CloseAbnormalClosure
	StatusInvalidFramePayloadData StatusCode = websocket.CloseInvalidFramePayloadData
	StatusPolicyViolation         StatusCode = websocket.ClosePolicyViolation
	StatusMessageTooBig           StatusCode = websocket.CloseMessageTooBig
	StatusMandatoryExtension      StatusCode = websocket.CloseMandatoryExtension
	StatusInternalServerError     StatusCode = websocket.CloseInternalServerErr
	StatusServiceRestart          StatusCode = websocket.CloseServiceRestart
	StatusTryAgainLater           StatusCode = websocket.CloseTryAgainLater
	StatusBadGateway              StatusCode = 1014 // Custom status code since gorilla doesn't have CloseBadGateway
)

WebSocket close status code constants.

Jump to

Keyboard shortcuts

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