websocket

package
v0.23.0 Latest Latest
Warning

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

Go to latest
Published: Oct 19, 2025 License: MIT Imports: 12 Imported by: 0

Documentation

Index

Constants

View Source
const (
	TextMessage   = ws.OpcodeText
	BinaryMessage = ws.OpcodeBinary
	CloseMessage  = ws.OpcodeClose
	PingMessage   = ws.OpcodePing
	PongMessage   = ws.OpcodePong
)

WebSocket message types

View Source
const (
	CloseNormalClosure           = ws.CloseNormalClosure
	CloseGoingAway               = ws.CloseGoingAway
	CloseProtocolError           = ws.CloseProtocolError
	CloseUnsupportedData         = ws.CloseUnsupportedData
	CloseNoStatusReceived        = ws.CloseNoStatusReceived
	CloseAbnormalClosure         = ws.CloseAbnormalClosure
	CloseInvalidFramePayloadData = ws.CloseInvalidFramePayloadData
	ClosePolicyViolation         = ws.ClosePolicyViolation
	CloseMessageTooBig           = ws.CloseMessageTooBig
	CloseMandatoryExtension      = ws.CloseMandatoryExtension
	CloseInternalServerError     = ws.CloseInternalServerError
	CloseServiceRestart          = ws.CloseServiceRestart
	CloseTryAgainLater           = ws.CloseTryAgainLater
	CloseTLSHandshake            = ws.CloseTLSHandshake
)

WebSocket close codes

Variables

View Source
var (
	ErrNotWebSocket = ws.ErrNotWebSocket
	ErrBadHandshake = ws.ErrBadHandshake
)

WebSocket errors

Functions

func CheckOriginWithAllowedList

func CheckOriginWithAllowedList(allowedOrigins []string) func(r *http.Request) bool

CheckOriginWithAllowedList checks if the origin is in the allowed list

func DefaultCheckOrigin

func DefaultCheckOrigin(r *http.Request) bool

DefaultCheckOrigin provides a safe default origin check that enforces same-origin policy

func IsCloseError

func IsCloseError(err error, codes ...int) bool

IsCloseError returns true if the error is a close error with one of the specified codes

func IsUnexpectedCloseError

func IsUnexpectedCloseError(err error, expectedCodes ...int) bool

IsUnexpectedCloseError checks if the error is an unexpected close error

Types

type Conn

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

Conn represents a WebSocket connection

func (*Conn) Close

func (c *Conn) Close() error

Close closes the WebSocket connection

func (*Conn) CloseHandler

func (c *Conn) CloseHandler() func(code int, text string) error

CloseHandler returns the current close handler

func (*Conn) LocalAddr

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

LocalAddr returns the local network address

func (*Conn) PingHandler

func (c *Conn) PingHandler() func(appData string) error

PingHandler returns the current ping handler

func (*Conn) PongHandler

func (c *Conn) PongHandler() func(appData string) error

PongHandler returns the current pong handler

func (*Conn) ReadJSON

func (c *Conn) ReadJSON(v interface{}) error

ReadJSON reads a JSON-encoded message from the connection

func (*Conn) ReadMessage

func (c *Conn) ReadMessage() (messageType int, p []byte, err error)

ReadMessage reads a message from the WebSocket connection

func (*Conn) RemoteAddr

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

RemoteAddr returns the remote network address

func (*Conn) SetCloseHandler

func (c *Conn) SetCloseHandler(h func(code int, text string) error)

SetCloseHandler sets the handler for close messages

func (*Conn) SetPingHandler

func (c *Conn) SetPingHandler(h func(appData string) error)

SetPingHandler sets the handler for ping messages

func (*Conn) SetPongHandler

func (c *Conn) SetPongHandler(h func(appData string) error)

SetPongHandler sets the handler for pong messages

func (*Conn) SetReadDeadline

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

SetReadDeadline sets the read deadline on the connection

func (*Conn) SetWriteDeadline

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

SetWriteDeadline sets the write deadline on the connection

func (*Conn) WriteControl

func (c *Conn) WriteControl(messageType int, data []byte, deadline time.Time) error

WriteControl writes a control message with the given deadline

func (*Conn) WriteJSON

func (c *Conn) WriteJSON(v interface{}) error

WriteJSON writes a JSON-encoded message to the connection

func (*Conn) WriteMessage

func (c *Conn) WriteMessage(messageType int, data []byte) error

WriteMessage writes a message to the WebSocket connection

type PoolConfig

type PoolConfig struct {
	// MaxConnectionsPerEndpoint is the maximum number of connections per endpoint
	MaxConnectionsPerEndpoint int

	// MaxIdleConnections is the maximum number of idle connections per endpoint
	MaxIdleConnections int

	// IdleTimeout is how long a connection can be idle before being closed
	IdleTimeout time.Duration

	// HealthCheckInterval is how often to ping connections to check health
	HealthCheckInterval time.Duration

	// ConnectionTimeout is the timeout for establishing new connections
	ConnectionTimeout time.Duration

	// EnableCompression enables WebSocket compression
	EnableCompression bool

	// OnConnectionCreated is called when a new connection is created
	OnConnectionCreated func(endpoint string, conn *Conn)

	// OnConnectionClosed is called when a connection is closed
	OnConnectionClosed func(endpoint string, conn *Conn, reason error)
}

PoolConfig configures the WebSocket connection pool

func DefaultPoolConfig

func DefaultPoolConfig() PoolConfig

DefaultPoolConfig returns a default pool configuration

type PoolStats

type PoolStats struct {
	TotalConnections   atomic.Int64
	ActiveConnections  atomic.Int64
	IdleConnections    atomic.Int64
	FailedConnections  atomic.Int64
	ConnectionsCreated atomic.Int64
	ConnectionsReused  atomic.Int64
	HealthChecksFailed atomic.Int64
}

PoolStats tracks pool statistics

type Upgrader

type Upgrader struct {
	// CheckOrigin returns true if the request Origin header is acceptable
	// If nil, a safe default is used that checks for same-origin requests
	CheckOrigin func(r *http.Request) bool

	// Subprotocols specifies the server's supported protocols in order of preference
	Subprotocols []string

	// Error specifies the function for generating HTTP error responses
	Error func(w http.ResponseWriter, r *http.Request, status int, reason error)

	// MaxMessageSize is the maximum size for a message read from the peer
	MaxMessageSize int64

	// WriteBufferSize is the size of the write buffer
	WriteBufferSize int

	// ReadBufferSize is the size of the read buffer
	ReadBufferSize int

	// HandshakeTimeout specifies the duration for the handshake to complete
	HandshakeTimeout time.Duration

	// EnableCompression specifies if the server should attempt to negotiate compression
	EnableCompression bool

	// BeforeUpgrade is called after origin check but before sending upgrade response
	// This can be used for authentication, rate limiting, or other pre-upgrade checks
	BeforeUpgrade func(w http.ResponseWriter, r *http.Request) error

	// AllowedOrigins is a list of allowed origins for CORS
	// If empty and CheckOrigin is nil, same-origin policy is enforced
	AllowedOrigins []string

	// RequireProtocol ensures the client specifies one of the supported subprotocols
	RequireProtocol bool
}

Upgrader upgrades HTTP connections to WebSocket connections

func (*Upgrader) Upgrade

func (u *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header) (*Conn, error)

Upgrade upgrades an HTTP connection to a WebSocket connection

type WebSocketPool

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

WebSocketPool manages a pool of WebSocket connections

func NewWebSocketPool

func NewWebSocketPool(config PoolConfig) *WebSocketPool

NewWebSocketPool creates a new WebSocket connection pool

func (*WebSocketPool) Close

func (p *WebSocketPool) Close(conn *Conn, reason error) error

Close closes a connection and removes it from the pool

func (*WebSocketPool) Get

func (p *WebSocketPool) Get(ctx context.Context, endpoint string, upgrader *Upgrader, w http.ResponseWriter, r *http.Request) (*Conn, error)

Get retrieves a connection from the pool or creates a new one

func (*WebSocketPool) GetStats

func (p *WebSocketPool) GetStats() PoolStats

GetStats returns current pool statistics

func (*WebSocketPool) Put

func (p *WebSocketPool) Put(conn *Conn) error

Put returns a connection to the pool

func (*WebSocketPool) Shutdown

func (p *WebSocketPool) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the pool

Jump to

Keyboard shortcuts

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