This commit is contained in:
laodaming 2023-08-24 12:18:04 +08:00
parent aa89a74c2b
commit dca54ee2b7

View File

@ -10,6 +10,7 @@ import (
"fusenapi/utils/auth"
"fusenapi/utils/encryption_decryption"
"net/http"
"strings"
"sync"
"time"
@ -90,6 +91,13 @@ func (l *DataTransferLogic) DataTransfer(w http.ResponseWriter, r *http.Request)
//设置Sec-Websocket-Protocol
upgrader.Subprotocols = []string{token}
}
//判断下是否火狐浏览器(获取浏览器第一条消息返回有收不到的bug需要延迟1秒)
userAgent := r.Header.Get("User-Agent")
//是否火狐浏览器
isFirefoxBrowser := false
if strings.Contains(userAgent, "Firefox") {
isFirefoxBrowser = true
}
//升级websocket
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
@ -104,12 +112,12 @@ func (l *DataTransferLogic) DataTransfer(w http.ResponseWriter, r *http.Request)
isAuth, userInfo = l.checkAuth(r)
if !isAuth {
//未授权响应消息
l.unAuthResponse(conn)
l.unAuthResponse(conn, isFirefoxBrowser)
conn.Close()
return
}
//设置连接
ws, err := l.setConnPool(conn, *userInfo)
ws, err := l.setConnPool(conn, *userInfo, isFirefoxBrowser)
if err != nil {
conn.Close()
return
@ -129,7 +137,7 @@ func (l *DataTransferLogic) DataTransfer(w http.ResponseWriter, r *http.Request)
}
// 设置连接
func (l *DataTransferLogic) setConnPool(conn *websocket.Conn, userInfo auth.UserInfo) (wsConnectItem, error) {
func (l *DataTransferLogic) setConnPool(conn *websocket.Conn, userInfo auth.UserInfo, isFirefoxBrowser bool) (wsConnectItem, error) {
publicMutex.Lock()
defer publicMutex.Unlock()
//生成连接唯一标识
@ -156,16 +164,10 @@ func (l *DataTransferLogic) setConnPool(conn *websocket.Conn, userInfo auth.User
}
//保存连接
mapConnPool.Store(uniqueId, ws)
go func() {
defer func() {
if err := recover(); err != nil {
logx.Error("set conn pool panic:", err)
}
}()
//把连接成功消息发回去
if isFirefoxBrowser {
time.Sleep(time.Second * 1) //兼容下火狐(直接发回去收不到第一条消息:有待研究)
ws.sendToOutChan(ws.respondDataFormat(constants.WEBSOCKET_CONNECT_SUCCESS, uniqueId))
}()
}
ws.sendToOutChan(ws.respondDataFormat(constants.WEBSOCKET_CONNECT_SUCCESS, uniqueId))
return ws, nil
}
@ -211,13 +213,15 @@ func (l *DataTransferLogic) checkAuth(r *http.Request) (isAuth bool, userInfo *a
}
// 鉴权失败通知
func (l *DataTransferLogic) unAuthResponse(conn *websocket.Conn) {
time.Sleep(time.Second * 1) //兼容下火狐(直接发回去收不到第一条消息:有待研究)
func (l *DataTransferLogic) unAuthResponse(conn *websocket.Conn, isFirefoxBrowser bool) {
rsp := websocket_data.DataTransferData{
T: constants.WEBSOCKET_UNAUTH,
D: nil,
}
b, _ := json.Marshal(rsp)
if isFirefoxBrowser {
time.Sleep(time.Second * 1) //兼容下火狐(直接发回去收不到第一条消息:有待研究)
}
//先发一条正常信息
_ = conn.WriteMessage(websocket.TextMessage, b)
//发送关闭信息