-
-
Notifications
You must be signed in to change notification settings - Fork 162
/
jsonPipe.go
64 lines (58 loc) · 1.27 KB
/
jsonPipe.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
package playwright
import (
"encoding/json"
"errors"
"fmt"
)
type jsonPipe struct {
channelOwner
msgChan chan *message
}
func (j *jsonPipe) Send(message map[string]interface{}) error {
_, err := j.channel.Send("send", map[string]interface{}{
"message": message,
})
return err
}
func (j *jsonPipe) Close() error {
_, err := j.channel.Send("close")
return err
}
func (j *jsonPipe) Poll() (*message, error) {
msg := <-j.msgChan
if msg == nil {
return nil, errors.New("jsonPipe closed")
}
return msg, nil
}
func newJsonPipe(parent *channelOwner, objectType string, guid string, initializer map[string]interface{}) *jsonPipe {
j := &jsonPipe{
msgChan: make(chan *message, 2),
}
j.createChannelOwner(j, parent, objectType, guid, initializer)
j.channel.On("message", func(ev map[string]interface{}) {
var msg message
m, err := json.Marshal(ev["message"])
if err == nil {
err = json.Unmarshal(m, &msg)
}
if err != nil {
msg = message{
Error: &struct {
Error Error "json:\"error\""
}{
Error: Error{
Name: "Error",
Message: fmt.Sprintf("jsonPipe: could not decode message: %s", err.Error()),
},
},
}
}
j.msgChan <- &msg
})
j.channel.Once("closed", func() {
j.Emit("closed")
close(j.msgChan)
})
return j
}