ws

package
v0.0.0-...-f93e24f Latest Latest
Warning

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

Go to latest
Published: Jul 16, 2026 License: Apache-2.0 Imports: 6 Imported by: 0

Documentation

Overview

Package ws 基于 github.com/coder/websocket 提供 WebSocket 的轻量封装: 自动完成握手升级、统一关闭语义,并把 *http.Request 透传给业务, 便于读取 query / header / 子协议 / 鉴权信息。

注意:WebSocket 升级依赖 http.Hijacker。otelhttp 会透传 Hijacker,可正常使用; 但不要给 WebSocket 路由套 compress 中间件(其 ResponseWriter 不直接实现 Hijacker)。

Index

Constants

View Source
const (
	// Text UTF-8 文本消息。
	Text = websocket.MessageText
	// Binary 二进制消息。
	Binary = websocket.MessageBinary
)
View Source
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

func Handler(fn func(r *http.Request, c *Conn) error, opts ...Option) http.HandlerFunc

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) Ping

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

Ping 发送 ping 并等待 pong,可用于探活。

func (*Conn) Raw

func (c *Conn) Raw() *websocket.Conn

Raw 返回底层 *websocket.Conn,用于本封装未覆盖的高级用法。

func (*Conn) Read

func (c *Conn) Read(ctx context.Context) (MessageType, []byte, error)

Read 读取一条消息,返回类型与内容。连接关闭或 ctx 取消时返回错误。

func (*Conn) ReadJSON

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

ReadJSON 读取一条消息并按 JSON 反序列化到 v。

func (*Conn) Subprotocol

func (c *Conn) Subprotocol() string

Subprotocol 返回握手协商出的子协议(未协商为空串)。

func (*Conn) Write

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

Write 写入一条指定类型的消息。

func (*Conn) WriteBinary

func (c *Conn) WriteBinary(ctx context.Context, b []byte) error

WriteBinary 写入一条二进制消息。

func (*Conn) WriteJSON

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

WriteJSON 将 v 序列化为 JSON 文本消息写出。

func (*Conn) WriteText

func (c *Conn) WriteText(ctx context.Context, s string) error

WriteText 写入一条文本消息。

type MessageType

type MessageType = websocket.MessageType

MessageType 表示消息类型(文本 / 二进制)。

type Option

type Option func(*config)

Option 配置 Handler 的握手行为。

func WithInsecureSkipVerify

func WithInsecureSkipVerify() Option

WithInsecureSkipVerify 关闭 origin 校验(仅开发/可信内网使用,生产慎用)。

func WithOriginPatterns

func WithOriginPatterns(patterns ...string) Option

WithOriginPatterns 允许这些 origin 跨域连接(path.Match 模式)。 默认仅允许同源。

func WithPingInterval

func WithPingInterval(d time.Duration) Option

WithPingInterval 启用后台心跳:每隔 d 向对端发送一次 ping, ping 失败(对端无响应或连接已坏)即关闭连接,便于检测半开 TCP。 d<=0(默认)表示不启用。

注意:ping 的 pong 由 Read 流程处理,因此心跳对“持续 Read 的连接”最有效; 对只写不读的连接,建议在 fn 内调用 c.Raw().CloseRead(ctx) 以在后台处理控制帧。

func WithReadLimit

func WithReadLimit(n int64) Option

WithReadLimit 设置单条消息读取上限(字节)。传 -1 表示不限制。 不设置时使用库默认(32KiB)。

func WithSubprotocols

func WithSubprotocols(s ...string) Option

WithSubprotocols 声明服务端支持的子协议,握手时与客户端协商。

type StatusCode

type StatusCode = websocket.StatusCode

StatusCode 是 WebSocket 关闭状态码。

Directories

Path Synopsis
Package session 提供基于 WebSocket 的有状态会话高阶封装。
Package session 提供基于 WebSocket 的有状态会话高阶封装。

Jump to

Keyboard shortcuts

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