fusenapi/server/websocket/internal/handler/datatransferhandler.go

84 lines
2.0 KiB
Go
Raw Normal View History

2023-07-24 08:07:05 +00:00
package handler
import (
2023-07-24 11:44:28 +00:00
"encoding/json"
"fusenapi/constants"
2023-07-24 08:07:05 +00:00
"fusenapi/server/websocket/internal/svc"
2023-07-24 11:44:28 +00:00
"fusenapi/server/websocket/internal/types"
"fusenapi/utils/auth"
"github.com/google/uuid"
2023-07-24 08:07:05 +00:00
"github.com/gorilla/websocket"
2023-07-24 11:44:28 +00:00
"github.com/zeromicro/go-zero/core/logx"
2023-07-24 08:07:05 +00:00
"net/http"
"sync"
2023-07-24 11:44:28 +00:00
"time"
2023-07-24 08:07:05 +00:00
)
var (
//升级
upgrade = websocket.Upgrader{
//允许跨域
CheckOrigin: func(r *http.Request) bool {
return true
},
}
//连接map池
mapConn = sync.Map{}
)
2023-07-24 11:44:28 +00:00
// 每个连接的连接属性
2023-07-24 08:07:05 +00:00
type wsConnectItem struct {
conn *websocket.Conn //websocket的连接
2023-07-24 11:44:28 +00:00
property interface{} //属性
2023-07-24 08:07:05 +00:00
}
func DataTransferHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
2023-07-24 11:44:28 +00:00
// 解析JWT token,并对空用户进行判断
2023-07-24 08:07:05 +00:00
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中获取对应的用户信息
2023-07-24 11:44:28 +00:00
_, err = auth.GetUserInfoFormMapClaims(claims)
2023-07-24 08:07:05 +00:00
// 如果获取用户信息出错,则返回未授权的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
2023-07-24 11:44:28 +00:00
}
//生成连接唯一标识
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)
2023-07-24 08:07:05 +00:00
}
}
2023-07-24 11:44:28 +00:00
func (w *wsConnectItem) Readloop() {
}