package handler import ( "encoding/json" "fusenapi/constants" "fusenapi/server/websocket/internal/svc" "fusenapi/server/websocket/internal/types" "fusenapi/utils/auth" "github.com/google/uuid" "github.com/gorilla/websocket" "github.com/zeromicro/go-zero/core/logx" "net/http" "sync" "time" ) var ( //升级 upgrade = websocket.Upgrader{ //允许跨域 CheckOrigin: func(r *http.Request) bool { return true }, } //连接map池 mapConn = sync.Map{} ) // 每个连接的连接属性 type wsConnectItem struct { conn *websocket.Conn //websocket的连接 property interface{} //属性 } func DataTransferHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { // 解析JWT token,并对空用户进行判断 claims, err := svcCtx.ParseJwtToken(r) // 如果解析JWT token出错,则返回未授权的JSON响应并记录错误消息 if err != nil { logx.Info("unauthorized:", err.Error()) // 记录错误日志 w.Write([]byte("connect failed:unauthorized")) return } if claims != nil { // 从token中获取对应的用户信息 _, err = auth.GetUserInfoFormMapClaims(claims) // 如果获取用户信息出错,则返回未授权的JSON响应并记录错误消息 if err != nil { return } } else { // 如果claims为nil,则认为用户身份为白板用户 w.Write([]byte("connect failed:unauthorized!!")) return } //升级websocket conn, err := upgrade.Upgrade(w, r, r.Header) if err != nil { logx.Error("http upgrade websocket err:", err) w.Write([]byte("http upgrade websocket err")) return } //生成连接唯一标识 uniqueId := uuid.New().String() + time.Now().Format("20060102150405") c := wsConnectItem{ conn: conn, } //保存连接 mapConn.Store(uniqueId, c) //把uniqueId传回去 rsp := types.DataTransferRsp{ MsgType: constants.WEBSOCKET_CONNECT_SUCCESS, Message: uniqueId, } b, _ := json.Marshal(rsp) conn.WriteMessage(websocket.TextMessage, b) } } func (w *wsConnectItem) Readloop() { }