WebSocket 事件注册

XYGo Admin 2026-04-22 1 次阅读

扩展中注册WebSocket事件处理器

如果你的扩展需要实时推送功能,可以注册自定义 WebSocket 事件。

注册方式

module.goinit() 中注册:

go 复制代码
package shop

import (
    "xygo/internal/addon"
    "xygo/internal/websocket"
)

func init() {
    addon.Register(addon.Module{
        Name: "shop",
        Mount: func(s *ghttp.Server) { /* 路由注册... */ },
    })

    // 注册 WebSocket 事件
    websocket.RegisterEvent("shop.orderNotify", handleOrderNotify)
    websocket.RegisterEvent("shop.stockAlert", handleStockAlert)
}

事件处理函数

go 复制代码
func handleOrderNotify(client *websocket.Client, req *websocket.WsRequest) {
    // req.Event = "shop.orderNotify"
    // req.Data  = map[string]interface{}{...} 前端发送的数据

    // 回复当前客户端
    client.SendMsg(websocket.NewResponse("shop.orderNotify", map[string]interface{}{
        "orderId": 12345,
        "status":  "paid",
    }))
}

func handleStockAlert(client *websocket.Client, req *websocket.WsRequest) {
    // 广播给所有在线用户
    websocket.Manager.Broadcast(websocket.NewResponse("shop.stockAlert", map[string]interface{}{
        "message": "库存不足",
    }))
}

核心 API

函数 说明
websocket.RegisterEvent(event, handler) 注册事件处理器
client.SendMsg(response) 向当前客户端发消息
websocket.Manager.Broadcast(response) 广播给所有在线客户端
websocket.SendToUser(userType, userId, response) 向指定用户发消息
websocket.NewResponse(event, data) 构造成功响应
websocket.NewErrorResponse(event, code, msg) 构造错误响应

事件命名规范

事件名使用 {扩展名}.{事件名} 格式,避免与其他扩展冲突:

复制代码
shop.orderNotify       ✓ 正确
shop.stockAlert        ✓ 正确
orderNotify            ✗ 避免(可能与其他扩展冲突)