admin_backend/util/websocket.go
2025-03-04 12:05:23 +08:00

36 lines
771 B
Go

package util
import (
"backend/common"
"fmt"
"golang.org/x/net/websocket"
)
func GetWebsocket(AppId, ServerId int) (*websocket.Conn, error) {
App, err := GetAppConfig(AppId)
if err != nil {
return nil, err
}
Server, err := common.GetServerConfig(App.ServerName)
if err != nil {
return nil, err
}
origin := "http://localhost/"
url := fmt.Sprintf("ws://%s:%d/", Server.Host, App.WsPort+ServerId)
config, err := websocket.NewConfig(url, origin)
if err != nil {
return nil, fmt.Errorf("failed to create websocket config: %v", err)
}
// config.Dialer = &net.Dialer{
// Timeout: 5 * time.Second,
// }
ws, err := websocket.DialConfig(config)
if err != nil {
return nil, fmt.Errorf("failed to connect to websocket: %v", err)
}
return ws, nil
}