ws

package
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Jul 13, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrHubNotRunning 在 Hub 未启动 Run 即调用 Try* 方法时返回。
	ErrHubNotRunning = errors.New("websocket hub not running")
	// ErrHubStopped 在 Hub 已 Stop 后调用 Try* 方法时返回。
	ErrHubStopped = errors.New("websocket hub stopped")
	// ErrHubQueueFull 在 register/unregister/broadcast channel 缓冲满时返回。
	ErrHubQueueFull = errors.New("websocket hub queue full")
	// ErrNilConnection 在向 Hub 注册/注销 nil 连接时返回。
	ErrNilConnection = errors.New("websocket connection is nil")
)
View Source
var ErrSendBufferFull = errors.New("websocket send buffer full")

ErrSendBufferFull 发送缓冲已满(消费者跟不上)。非阻塞投递策略下返回此错误, 调用方可决定重试或关闭连接。避免慢消费者阻塞发送方(含 Hub 广播持锁场景)。

Functions

func AllowOrigins added in v1.2.0

func AllowOrigins(origins ...string) func(r *http.Request) bool

AllowOrigins 返回一个 CheckOrigin 函数,仅放行给定 Origin 列表(含 scheme+host[:port])。 用于多可信域名场景。传入空切片等价于拒绝所有带 Origin 的浏览器连接。

func Handle

func Handle(handler Handler) gin.HandlerFunc

Handle WebSocket 处理中间件

func HandleFunc

func HandleFunc(fn HandlerFunc) gin.HandlerFunc

HandleFunc 使用函数处理 WebSocket

func SetCheckOrigin

func SetCheckOrigin(fn func(r *http.Request) bool)

SetCheckOrigin 设置 Origin 检查函数。传 nil 会恢复默认同源校验。 运行期并发调用安全:upgrader 持有固定 wrapper,实际检查函数经 atomic.Value 切换。

Types

type Connection

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

Connection WebSocket 连接

func NewConnection

func NewConnection(conn *websocket.Conn) *Connection

NewConnection 创建 WebSocket 连接

func Upgrade

func Upgrade(c *gin.Context) (*Connection, error)

Upgrade 升级 HTTP 连接为 WebSocket

func (*Connection) Close

func (c *Connection) Close()

Close 关闭连接。仅 close closeChan 作关闭信号,不 close send channel(C2b 修复), 避免 Close 与并发 Send 之间的 send-on-closed panic。send channel 由 GC 回收。

func (*Connection) IsClosed

func (c *Connection) IsClosed() bool

IsClosed 检查连接是否已关闭

func (*Connection) Send

func (c *Connection) Send(data []byte) error

Send 非阻塞发送消息。不直接写底层 conn,而是投递到 send channel 由 writePump 统一写出。

并发安全说明(C2b 修复):Close() 仅 close closeChan,不再 close send channel, 因此 select 选中 send 分支也只是向未关闭 channel 投递(不会 panic)。

非阻塞策略(C2a-residual 修复):投递用 default 分支,缓冲满立即返回 ErrSendBufferFull, 而非阻塞等待。这避免 Hub 广播持锁期间因慢消费者/已死连接(writePump 退出但 closeChan 未关、send 缓冲满)阻塞最长 pongWait,导致整个 Hub stall。调用方对缓冲满可重试或关闭连接。

func (*Connection) SendJSON

func (c *Connection) SendJSON(v any) error

SendJSON 发送 JSON 消息

func (*Connection) SendText

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

SendText 发送文本消息

func (*Connection) SetReadDeadline

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

SetReadDeadline 设置读取超时

func (*Connection) SetWriteDeadline

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

SetWriteDeadline 设置写入超时

type DefaultHandler

type DefaultHandler struct {
	OnConnectFunc func(conn *Connection)
	OnMessageFunc func(conn *Connection, message []byte)
	OnCloseFunc   func(conn *Connection)
	OnErrorFunc   func(conn *Connection, err error)
}

DefaultHandler 默认处理器

func (*DefaultHandler) OnClose

func (h *DefaultHandler) OnClose(conn *Connection)

func (*DefaultHandler) OnConnect

func (h *DefaultHandler) OnConnect(conn *Connection)

func (*DefaultHandler) OnError

func (h *DefaultHandler) OnError(conn *Connection, err error)

func (*DefaultHandler) OnMessage

func (h *DefaultHandler) OnMessage(conn *Connection, message []byte)

type Handler

type Handler interface {
	OnConnect(conn *Connection)
	OnMessage(conn *Connection, message []byte)
	OnClose(conn *Connection)
	OnError(conn *Connection, err error)
}

Handler WebSocket 处理器接口

type HandlerFunc

type HandlerFunc func(conn *Connection, message []byte)

HandlerFunc 处理函数类型

type Hub

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

Hub 连接管理中心(用于广播)。 W1 修复:添加 stop channel + Stop() 方法,支持优雅退出。

func NewHub

func NewHub() *Hub

NewHub 创建 Hub

func (*Hub) Broadcast

func (h *Hub) Broadcast(message []byte)

Broadcast 广播消息。调用兼容旧 API:失败时直接返回。

func (*Hub) BroadcastJSON

func (h *Hub) BroadcastJSON(v any) error

BroadcastJSON 广播 JSON 消息

func (*Hub) Count

func (h *Hub) Count() int

Count 获取连接数

func (*Hub) Register

func (h *Hub) Register(conn *Connection)

Register 注册连接。调用兼容旧 API:失败时关闭连接并直接返回。

func (*Hub) Run

func (h *Hub) Run()

Run 运行 Hub。消费 register/unregister/broadcast/stop 四个 channel。

W1 修复:新增 stop 退出分支,Stop() 方法 close(stop) 通知退出。 死锁修复(C2a):广播分支不再向自身 unregister channel 回环。

H-9 修复:用 runOnce 守卫 Run 仅执行一次;用 runDone channel 替代 WaitGroup。 原实现 wg.Add(1) 在 Run 内、wg.Wait() 在 Stop 内,二者并发时违反 WaitGroup "Add(正delta且计数器为0) 必须 happens-before Wait" 的约束,-race 必采。 改为 Run 启动时 Store runStarted=true 并在退出时 close(runDone);Stop 仅在 runStarted 为 true 时 <-runDone 等待,未启动则直接返回,无竞态。

func (*Hub) Stop added in v1.2.0

func (h *Hub) Stop()

Stop 停止 Hub(W1 修复:优雅退出机制)。 close(stop) 通知 Run() 退出;若 Run 已启动则等待其完全结束(<-runDone)。

H-8 修复:用 stopOnce 保证 close(stop) 仅执行一次。原实现 select{<-stop/default:close(stop)} 在并发 Stop 时两个调用方都可能走 default 分支同时 close → double-close panic; 原注释声称的"stopped 标志保护"实际不存在(文档撒谎)。stopOnce 彻底消除该竞态。

H-9 修复:仅在 runStarted 为 true 时等待 runDone;Run 未启动时直接返回, 避免 WaitGroup Add/Wait 竞态,且 Stop 先于 Run 调用后误再调 Run 也不会 panic。 幂等:重复/并发调用安全。 Stop discards pending broadcast messages instead of guaranteeing delivery; it is a shutdown boundary. Pending register/unregister entries are drained and all live connections are closed before Stop returns.

func (*Hub) TryBroadcast added in v1.3.0

func (h *Hub) TryBroadcast(message []byte) error

TryBroadcast 广播消息并返回失败原因。

func (*Hub) TryRegister added in v1.3.0

func (h *Hub) TryRegister(conn *Connection) error

TryRegister 注册连接并返回失败原因。Hub 未 Run、已 Stop 或队列满时立即返回错误。

func (*Hub) TryUnregister added in v1.3.0

func (h *Hub) TryUnregister(conn *Connection) error

TryUnregister 注销连接并返回失败原因。

func (*Hub) Unregister

func (h *Hub) Unregister(conn *Connection)

Unregister 注销连接。调用兼容旧 API:失败时直接返回。

type Message

type Message struct {
	Type    MessageType `json:"type"`
	Content any         `json:"content"`
}

Message WebSocket 消息

type MessageType

type MessageType string

MessageType 消息类型

const (
	TypeText   MessageType = "text"   // 文本消息
	TypeBinary MessageType = "binary" // 二进制消息
	TypePing   MessageType = "ping"   // 心跳 ping
	TypePong   MessageType = "pong"   // 心跳 pong
	TypeClose  MessageType = "close"  // 关闭消息
)

Jump to

Keyboard shortcuts

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