diff --git a/constants/websocket.go b/constants/websocket.go new file mode 100644 index 00000000..95bea53d --- /dev/null +++ b/constants/websocket.go @@ -0,0 +1,11 @@ +package constants + +type websocket string + +// websocket消息类型 +const ( + //ws连接成功 + WEBSOCKET_CONNECT_SUCCESS = "connect-success" + //图片渲染 + WEBSOCKET_RENDER_IMAGE = "render-image" +) diff --git a/server/websocket/internal/handler/datatransferhandler.go b/server/websocket/internal/handler/datatransferhandler.go index 4534d041..e1458960 100644 --- a/server/websocket/internal/handler/datatransferhandler.go +++ b/server/websocket/internal/handler/datatransferhandler.go @@ -1,10 +1,17 @@ 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 ( @@ -19,14 +26,15 @@ var ( mapConn = sync.Map{} ) +// 每个连接的连接属性 type wsConnectItem struct { conn *websocket.Conn //websocket的连接 - renImage sync.Map //需要渲染的图片 + property interface{} //属性 } func DataTransferHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - /*// 解析JWT token,并对空用户进行判断 + // 解析JWT token,并对空用户进行判断 claims, err := svcCtx.ParseJwtToken(r) // 如果解析JWT token出错,则返回未授权的JSON响应并记录错误消息 if err != nil { @@ -34,10 +42,9 @@ func DataTransferHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { w.Write([]byte("connect failed:unauthorized")) return } - var userInfo *auth.UserInfo if claims != nil { // 从token中获取对应的用户信息 - userInfo, err = auth.GetUserInfoFormMapClaims(claims) + _, err = auth.GetUserInfoFormMapClaims(claims) // 如果获取用户信息出错,则返回未授权的JSON响应并记录错误消息 if err != nil { return @@ -53,6 +60,24 @@ func DataTransferHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { 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() { + +}