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