package controller import ( "aiChat/internal/model" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/net/ghttp" "github.com/gogf/gf/v2/os/gctx" "github.com/gogf/gf/v2/os/glog" ) // ChatWs 聊天websocket请求 var ChatWs = func(r *ghttp.Request) { session, _ := model.GetSession(r) wsChat := model.NewMessage(gctx.New(), session.AccountId) // 创建ws链接 ws, err := r.WebSocket() if err != nil { glog.Error(wsChat.Ctx, session.AccountId, "建立连接出错", err) r.Exit() } if session.AccountId == 0 { _ = ws.WriteJSON(g.Map{ "error_code": -1, "error_msg": "无用户身份", }) return } for { // 接受客户端信息 _, msg, err := ws.ReadMessage() if err != nil { glog.Info(wsChat.Ctx, session.AccountId, "接收消息出错", err) _ = ws.Close() return } // 处理ws wsChat.Handle(ws, msg, r.GetClientIp(), r.UserAgent()) } }