forked from mbk-lab/rui_orig
2
0
Fork 0
rui/webBrige.go

122 lines
2.5 KiB
Go
Raw Normal View History

2022-10-27 16:14:30 +03:00
//go:build !wasm
2021-09-07 17:36:50 +03:00
package rui
import (
"net/http"
"strconv"
"sync"
"github.com/gorilla/websocket"
)
type wsBrige struct {
conn *websocket.Conn
answer map[int]chan DataObject
answerID int
answerMutex sync.Mutex
closed bool
}
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 8096,
}
2022-10-27 16:14:30 +03:00
func CreateSocketBrige(w http.ResponseWriter, req *http.Request) webBrige {
2021-09-07 17:36:50 +03:00
conn, err := upgrader.Upgrade(w, req, nil)
if err != nil {
ErrorLog(err.Error())
return nil
}
brige := new(wsBrige)
brige.answerID = 1
brige.answer = make(map[int]chan DataObject)
brige.conn = conn
brige.closed = false
return brige
}
2022-10-27 16:14:30 +03:00
func (brige *wsBrige) close() {
2021-09-07 17:36:50 +03:00
brige.closed = true
brige.conn.Close()
}
2022-10-27 16:14:30 +03:00
func (brige *wsBrige) readMessage() (string, bool) {
2021-09-07 17:36:50 +03:00
_, p, err := brige.conn.ReadMessage()
if err != nil {
if !brige.closed {
ErrorLog(err.Error())
}
return "", false
}
return string(p), true
}
2022-10-27 16:14:30 +03:00
func (brige *wsBrige) writeMessage(script string) bool {
2021-09-07 17:36:50 +03:00
if ProtocolInDebugLog {
DebugLog("Run script:")
DebugLog(script)
}
if err := brige.conn.WriteMessage(websocket.TextMessage, []byte(script)); err != nil {
ErrorLog(err.Error())
return false
}
return true
}
2022-10-27 16:14:30 +03:00
func (brige *wsBrige) runGetterScript(script string) DataObject {
2021-09-07 17:36:50 +03:00
brige.answerMutex.Lock()
answerID := brige.answerID
brige.answerID++
brige.answerMutex.Unlock()
answer := make(chan DataObject)
brige.answer[answerID] = answer
errorText := ""
if brige.conn != nil {
script = "var answerID = " + strconv.Itoa(answerID) + ";\n" + script
if ProtocolInDebugLog {
DebugLog("\n" + script)
}
err := brige.conn.WriteMessage(websocket.TextMessage, []byte(script))
if err == nil {
return <-answer
}
errorText = err.Error()
} else {
if ProtocolInDebugLog {
DebugLog("\n" + script)
}
errorText = "No connection"
}
result := NewDataObject("error")
result.SetPropertyValue("text", errorText)
delete(brige.answer, answerID)
return result
}
2022-10-27 16:14:30 +03:00
func (brige *wsBrige) answerReceived(answer DataObject) {
2021-09-07 17:36:50 +03:00
if text, ok := answer.PropertyValue("answerID"); ok {
if id, err := strconv.Atoi(text); err == nil {
if chanel, ok := brige.answer[id]; ok {
chanel <- answer
delete(brige.answer, id)
} else {
ErrorLog("Bad answerID = " + text + " (chan not found)")
}
} else {
ErrorLog("Invalid answerID = " + text)
}
} else {
ErrorLog("answerID not found")
}
}
func (brige *wsBrige) remoteAddr() string {
return brige.conn.RemoteAddr().String()
}