This commit is contained in:
laodaming 2023-07-24 19:44:28 +08:00
parent 25c3de6b99
commit 5fadf0697d
2 changed files with 41 additions and 5 deletions

11
constants/websocket.go Normal file
View File

@ -0,0 +1,11 @@
package constants
type websocket string
// websocket消息类型
const (
//ws连接成功
WEBSOCKET_CONNECT_SUCCESS = "connect-success"
//图片渲染
WEBSOCKET_RENDER_IMAGE = "render-image"
)

View File

@ -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() {
}