2022-11-24 23:37:34 +08:00
|
|
|
// Package websocket
|
|
|
|
// @Link https://github.com/bufanyun/hotgo
|
2023-02-23 17:53:04 +08:00
|
|
|
// @Copyright Copyright (c) 2023 HotGo CLI
|
2022-11-24 23:37:34 +08:00
|
|
|
// @Author Ms <133814250@qq.com>
|
|
|
|
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
|
|
|
|
package websocket
|
|
|
|
|
|
|
|
import (
|
2023-06-25 19:22:08 +08:00
|
|
|
"context"
|
2022-11-24 23:37:34 +08:00
|
|
|
"github.com/gogf/gf/v2/frame/g"
|
|
|
|
"github.com/gogf/gf/v2/util/gconv"
|
|
|
|
"runtime/debug"
|
|
|
|
)
|
|
|
|
|
|
|
|
// handlerMsg 处理消息
|
|
|
|
func handlerMsg(client *Client, message []byte) {
|
|
|
|
defer func() {
|
|
|
|
if r := recover(); r != nil {
|
2023-08-02 17:38:40 +08:00
|
|
|
g.Log().Warningf(mctx, "handlerMsg recover, err:%+v, stack:%+v", r, string(debug.Stack()))
|
2022-11-24 23:37:34 +08:00
|
|
|
}
|
|
|
|
}()
|
2023-02-26 14:18:22 +08:00
|
|
|
|
|
|
|
var request *WRequest
|
|
|
|
if err := gconv.Struct(message, &request); err != nil {
|
2023-08-02 17:38:40 +08:00
|
|
|
g.Log().Warningf(mctx, "handlerMsg 数据解析失败,err:%+v, message:%+v", err, string(message))
|
2022-11-24 23:37:34 +08:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if request.Event == "" {
|
2023-08-02 17:38:40 +08:00
|
|
|
g.Log().Warning(mctx, "handlerMsg request.Event is null")
|
2022-11-24 23:37:34 +08:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
fun, ok := routers[request.Event]
|
|
|
|
if !ok {
|
2023-08-02 17:38:40 +08:00
|
|
|
g.Log().Warningf(mctx, "handlerMsg function id %v: not registered", request.Event)
|
2022-11-24 23:37:34 +08:00
|
|
|
return
|
|
|
|
}
|
2023-06-25 19:22:08 +08:00
|
|
|
|
2023-08-02 17:38:40 +08:00
|
|
|
err := msgGo.AddWithRecover(mctx,
|
2023-06-25 19:22:08 +08:00
|
|
|
func(ctx context.Context) {
|
|
|
|
fun(client, request)
|
|
|
|
},
|
|
|
|
func(ctx context.Context, err error) {
|
2023-08-02 17:38:40 +08:00
|
|
|
g.Log().Warningf(mctx, "handlerMsg msgGo exec err:%+v", err)
|
2023-06-25 19:22:08 +08:00
|
|
|
},
|
|
|
|
)
|
|
|
|
|
|
|
|
if err != nil {
|
2023-08-02 17:38:40 +08:00
|
|
|
g.Log().Warningf(mctx, "handlerMsg msgGo Add err:%+v", err)
|
2023-06-25 19:22:08 +08:00
|
|
|
return
|
|
|
|
}
|
2022-11-24 23:37:34 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// RegisterMsg 注册消息
|
|
|
|
func RegisterMsg(handlers EventHandlers) {
|
|
|
|
for id, f := range handlers {
|
|
|
|
if _, ok := routers[id]; ok {
|
2023-08-02 17:38:40 +08:00
|
|
|
g.Log().Fatalf(mctx, "RegisterMsg function id %v: already registered", id)
|
2022-11-24 23:37:34 +08:00
|
|
|
return
|
|
|
|
}
|
|
|
|
routers[id] = f
|
|
|
|
}
|
|
|
|
}
|