forked from playwright-community/playwright-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebsocket.go
81 lines (73 loc) · 1.83 KB
/
websocket.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package playwright
import (
"encoding/base64"
"log"
)
type webSocketImpl struct {
channelOwner
isClosed bool
}
func (ws *webSocketImpl) URL() string {
return ws.initializer["url"].(string)
}
func newWebsocket(parent *channelOwner, objectType string, guid string, initializer map[string]interface{}) *webSocketImpl {
ws := &webSocketImpl{}
ws.createChannelOwner(ws, parent, objectType, guid, initializer)
ws.channel.On("close", func() {
ws.Lock()
ws.isClosed = true
ws.Unlock()
ws.Emit("close")
})
ws.channel.On(
"frameSent",
func(params map[string]interface{}) {
ws.onFrameSent(params["opcode"].(float64), params["data"].(string))
},
)
ws.channel.On(
"frameReceived",
func(params map[string]interface{}) {
ws.onFrameReceived(params["opcode"].(float64), params["data"].(string))
},
)
ws.channel.On(
"error",
func(params map[string]interface{}) {
ws.Emit("error", params["error"])
},
)
return ws
}
func (ws *webSocketImpl) onFrameSent(opcode float64, data string) {
if opcode == 2 {
payload, err := base64.StdEncoding.DecodeString(data)
if err != nil {
log.Printf("could not decode WebSocket.onFrameSent payload: %v", err)
return
}
ws.Emit("framesent", payload)
} else {
ws.Emit("framesent", []byte(data))
}
}
func (ws *webSocketImpl) onFrameReceived(opcode float64, data string) {
if opcode == 2 {
payload, err := base64.StdEncoding.DecodeString(data)
if err != nil {
log.Printf("could not decode WebSocket.onFrameReceived payload: %v", err)
return
}
ws.Emit("framereceived", payload)
} else {
ws.Emit("framereceived", []byte(data))
}
}
func (ws *webSocketImpl) WaitForEvent(event string, predicate ...interface{}) interface{} {
return <-waitForEvent(ws, event, predicate...)
}
func (ws *webSocketImpl) IsClosed() bool {
ws.RLock()
defer ws.RUnlock()
return ws.isClosed
}