Documentation
¶
Overview ¶
Package ws 基于 github.com/coder/websocket 提供 WebSocket 的轻量封装: 自动完成握手升级、统一关闭语义,并把 *http.Request 透传给业务, 便于读取 query / header / 子协议 / 鉴权信息。
注意:WebSocket 升级依赖 http.Hijacker。otelhttp 会透传 Hijacker,可正常使用; 但不要给 WebSocket 路由套 compress 中间件(其 ResponseWriter 不直接实现 Hijacker)。
Index ¶
- Constants
- func BroadcastJSON[T any](b *stream.Broadcaster[T], opts ...Option) http.HandlerFunc
- func Handler(fn func(r *http.Request, c *Conn) error, opts ...Option) http.HandlerFunc
- type Conn
- func (c *Conn) Close(code StatusCode, reason string) error
- func (c *Conn) Ping(ctx context.Context) error
- func (c *Conn) Raw() *websocket.Conn
- func (c *Conn) Read(ctx context.Context) (MessageType, []byte, error)
- func (c *Conn) ReadJSON(ctx context.Context, v any) error
- func (c *Conn) Subprotocol() string
- func (c *Conn) Write(ctx context.Context, typ MessageType, data []byte) error
- func (c *Conn) WriteBinary(ctx context.Context, b []byte) error
- func (c *Conn) WriteJSON(ctx context.Context, v any) error
- func (c *Conn) WriteText(ctx context.Context, s string) error
- type MessageType
- type Option
- type StatusCode
Constants ¶
const ( // Text UTF-8 文本消息。 Text = websocket.MessageText // Binary 二进制消息。 Binary = websocket.MessageBinary )
const ( StatusNormalClosure = websocket.StatusNormalClosure StatusGoingAway = websocket.StatusGoingAway StatusInternalError = websocket.StatusInternalError )
Variables ¶
This section is empty.
Functions ¶
func BroadcastJSON ¶
func BroadcastJSON[T any](b *stream.Broadcaster[T], opts ...Option) http.HandlerFunc
BroadcastJSON 返回一个只推送的 WebSocket handler:每个连接订阅 b, 把广播来的每个值以 JSON 文本帧发给客户端。连接断开时自动退订。
它在后台 CloseRead 以处理客户端的 ping/pong 与关闭帧(写多读少场景的推荐做法)。
bc := stream.New[Notice](stream.WithBufferSize(64))
mux.Handle("/ws/notice", ws.BroadcastJSON(bc))
// 业务侧:bc.Publish(Notice{...})
func Handler ¶
Handler 把请求升级为 WebSocket 并执行 fn。
- fn 接收 *http.Request,可读取 query / header / 子协议 / 鉴权信息; 取消信号通过 r.Context() 获取。
- fn 返回 nil:正常关闭(StatusNormalClosure)。
- fn 返回 error:以 StatusInternalError 关闭。
握手失败时 Accept 已自行写出错误响应,Handler 直接返回。
mux.Handle("/ws", ws.Handler(func(r *http.Request, c *ws.Conn) error {
ctx := r.Context()
for {
typ, data, err := c.Read(ctx)
if err != nil { return err } // 客户端关闭/出错即退出
if err := c.Write(ctx, typ, data); err != nil { return err }
}
}))
Types ¶
type Conn ¶
type Conn struct {
// contains filtered or unexported fields
}
Conn 是对 websocket 连接的薄封装。
func (*Conn) Close ¶
func (c *Conn) Close(code StatusCode, reason string) error
Close 以指定状态码主动关闭连接(发送关闭帧)。
func (*Conn) WriteBinary ¶
WriteBinary 写入一条二进制消息。
type Option ¶
type Option func(*config)
Option 配置 Handler 的握手行为。
func WithInsecureSkipVerify ¶
func WithInsecureSkipVerify() Option
WithInsecureSkipVerify 关闭 origin 校验(仅开发/可信内网使用,生产慎用)。
func WithOriginPatterns ¶
WithOriginPatterns 允许这些 origin 跨域连接(path.Match 模式)。 默认仅允许同源。
func WithPingInterval ¶
WithPingInterval 启用后台心跳:每隔 d 向对端发送一次 ping, ping 失败(对端无响应或连接已坏)即关闭连接,便于检测半开 TCP。 d<=0(默认)表示不启用。
注意:ping 的 pong 由 Read 流程处理,因此心跳对“持续 Read 的连接”最有效; 对只写不读的连接,建议在 fn 内调用 c.Raw().CloseRead(ctx) 以在后台处理控制帧。
func WithReadLimit ¶
WithReadLimit 设置单条消息读取上限(字节)。传 -1 表示不限制。 不设置时使用库默认(32KiB)。
func WithSubprotocols ¶
WithSubprotocols 声明服务端支持的子协议,握手时与客户端协商。