Documentation
¶
Overview ¶
Package ws provides WebSocket connection utilities including reading, writing, and lifecycle management.
Index ¶
- func IsErrWebsocketAlreadyClosed(err error) bool
- func IsErrWebsocketClosed(err error) bool
- func LogWebsocketReadError(ctx context.Context, err error)
- func LogWebsocketWriteError(ctx context.Context, targetName string, err error)
- type AcceptOption
- type BufferPool
- type CloseError
- type Conn
- func (w *Conn) AsyncWriter(ctx context.Context, messageType MessageType) (io.WriteCloser, error)
- func (w *Conn) Close(code StatusCode, reason string) error
- func (w *Conn) Flush(ctx context.Context) error
- func (w *Conn) GetStats() ConnStats
- func (w *Conn) Ping(ctx context.Context) error
- func (w *Conn) ReadJSON(ctx context.Context, v any) error
- func (w *Conn) Reader(ctx context.Context) (Reader, error)
- func (w *Conn) SetReadDeadline(t time.Time) error
- func (w *Conn) SetReadLimit(n int64)
- func (w *Conn) Subprotocol() string
- func (w *Conn) Write(ctx context.Context, messageType MessageType, data []byte) error
- func (w *Conn) WriteAsync(ctx context.Context, messageType MessageType, data []byte) error
- func (w *Conn) WriteAsyncFromReader(ctx context.Context, reader Reader) error
- func (w *Conn) WriteFromReader(ctx context.Context, reader Reader) error
- func (w *Conn) WriteJSON(ctx context.Context, v any) error
- func (w *Conn) WriteJSONAsync(ctx context.Context, obj any) error
- func (w *Conn) Writer(ctx context.Context, messageType MessageType) (io.WriteCloser, error)
- type ConnOption
- type ConnStats
- type DialOption
- type MessageType
- type Reader
- type StatusCode
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func IsErrWebsocketAlreadyClosed ¶
IsErrWebsocketAlreadyClosed reports whether err indicates the websocket was already closed.
func IsErrWebsocketClosed ¶
IsErrWebsocketClosed reports whether err indicates the websocket was closed.
func LogWebsocketReadError ¶
LogWebsocketReadError logs a websocket read error 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 ¶
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 ¶
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 ¶
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) ReadJSON ¶
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 ¶
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 ¶
SetReadDeadline sets the read deadline on the underlying connection. Setting a deadline in the past unblocks a pending Reader() call.
func (*Conn) SetReadLimit ¶
SetReadLimit sets the maximum size of incoming messages.
func (*Conn) Subprotocol ¶
Subprotocol returns the negotiated subprotocol.
func (*Conn) Write ¶
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 ¶
WriteAsync writes a message asynchronously via a background goroutine.
func (*Conn) WriteAsyncFromReader ¶
WriteAsyncFromReader writes data from a Reader asynchronously via a background goroutine.
func (*Conn) WriteFromReader ¶
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 ¶
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 ¶
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) LastSeenAt ¶
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.