mws

package
v0.3.1 Latest Latest
Warning

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

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

README

mws — 轻量的 WebSocket 封装

这是一个基于 github.com/gorilla/websocket 的轻量封装,放在仓库的 mws 包中,目标是提供简单、易用的 WebSocket 客户端/服务端升级与读写接口,适合在示例或小型服务中直接使用。

主要特性:

  • 提供 Conn 封装(包裹 *websocket.Conn),包含常用的 JSON/text 读写方法。
  • 提供 Upgrade 帮助函数,将 HTTP 请求升级为 WebSocket 连接(基于 websocket.Upgrader)。
  • 提供 DialContext 以 context 为入参的客户端连接方法。
  • 简单的 SimpleEchoHandler 示例 handler,用于 demo。

快速开始

# 启动 demo server(在仓库根目录下运行):
go run ./mws/ws_server_demo

# 在另一个终端运行 client:
go run ./mws/ws_client_demo

(注意:示例里 server 监听在 127.0.0.1:9999,client 默认连接 ws://127.0.0.1:9999/ws

API 概览

包内实现的主要符号:

  • type Conn — 封装的连接类型,方法包括:

    • WriteJSON(v any) error — 使用默认发送超时写入 JSON。
    • ReadJSON(v any) error — 读取 JSON 消息并解码到 v
    • WriteMessage(msgType int, data []byte) error — 写入文本/二进制消息。
    • ReadMessage() (int, []byte, error) — 读取原始消息(返回 message type + bytes)。
    • SetDeadlines(send, read time.Duration) — 设置默认的发送与读取超时时间(0 表示不使用超时)。
    • Close() error — 关闭连接。
  • func NewConn(ws *websocket.Conn) *Conn — 包装已存在的 *websocket.Conn

  • func DialContext(ctx context.Context, urlStr string, requestHeader http.Header) (*Conn, *http.Response, error) — 使用默认 dialer 发起客户端连接。

  • var Upgrader websocket.Upgrader — 提供默认 Upgrader(默认允许所有 origin,示例便于开发测试)。

  • func Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header) (*Conn, error) — 将 HTTP 请求升级为 WebSocket。

  • func SimpleEchoHandler() http.Handler — 一个简单的 echo handler,用于示例和快速验证。

示例(服务端):

http.Handle("/ws", mws.SimpleEchoHandler())
log.Fatal(http.ListenAndServe(":8080", nil))

示例(客户端):

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

conn, _, err := mws.DialContext(ctx, "ws://localhost:8080/ws", http.Header{})
defer conn.Close()

_ = conn.WriteMessage(websocket.TextMessage, []byte("hello"))
_, msg, _ := conn.ReadMessage()
fmt.Println(string(msg))

生产注意事项

  • Origin 校验:当前 Upgrader.CheckOrigin 默认为允许所有来源(方便开发和 demo)。在生产环境中,请务必实现更严格的校验,或覆盖 Upgrader.CheckOrigin
  • 并发写:github.com/gorilla/websocket 要求写操作必须串行化(不能并发写)。当前封装为轻量示例,并没有内部自动序列化写操作;如果你的应用会有多个 goroutine 同时写入,请为 Conn 添加写入队列或外部同步(例如单个写协程或 mutex)。
  • 超时设置:默认发送超时为 10 秒,读超时默认禁用。请根据网络与业务特性调整 SetDeadlines
  • 资源回收:确保在连接不再使用时调用 Close(),并对长连接做心跳/超时管理以避免资源泄漏。

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrInvalidURL = errors.New("invalid websocket url")

ErrInvalidURL 在提供的 URL 为空时返回。

View Source
var Upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
	CheckOrigin: func(r *http.Request) bool {

		return true
	},
}

Upgrader 使用合理的默认值封装了 websocket.Upgrader。

Functions

func SimpleEchoHandler

func SimpleEchoHandler() http.Handler

SimpleEchoHandler 返回一个 http.Handler,会将请求升级为 websocket 并将文本消息回显(作为相同消息)。

Types

type Conn

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

Conn 是对 websocket.Conn 的薄封装,提供 JSON/文本 的读写、简单的超时辅助和安全关闭。

func DialContext

func DialContext(ctx context.Context, urlStr string, requestHeader http.Header) (*Conn, *http.Response, error)

DialContext 连接(拨号)到一个 websocket 服务器并返回封装后的 Conn。

func NewConn

func NewConn(ws *websocket.Conn) *Conn

NewConn 用来封装一个已存在的 *websocket.Conn

func Upgrade

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

Upgrade 将 HTTP 请求升级为 websocket 连接并返回封装后的 Conn。

func (*Conn) Close

func (c *Conn) Close() error

Close 关闭底层连接。

func (*Conn) ReadJSON

func (c *Conn) ReadJSON(v any) error

ReadJSON 将下一个 JSON 消息读取到 v 中。如果设置了读取截止时间,则会应用该截止时间。

func (*Conn) ReadMessage

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

ReadMessage 从连接中读取单个消息。

func (*Conn) SetDeadlines

func (c *Conn) SetDeadlines(send, read time.Duration)

SetDeadlines 设置发送和读取操作的默认截止时间。

func (*Conn) WriteJSON

func (c *Conn) WriteJSON(v any) error

WriteJSON 使用配置的发送截止时间将 v 写为 JSON。

func (*Conn) WriteMessage

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

WriteMessage 写入一个文本或二进制消息。msgType 应为 websocket.TextMessage 或 websocket.BinaryMessage。

websocket.TextMessage (值通常为 1)—— 文本消息(UTF-8 编码) websocket.BinaryMessage (值通常为 2)—— 二进制消息 websocket.CloseMessage (控制帧,值通常为 8) websocket.PingMessage、websocket.PongMessage(控制帧)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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