-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathemit.go
68 lines (58 loc) · 1.26 KB
/
emit.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
package main
import (
"encoding/json"
"fmt"
)
// EmitMessage contains a parsed SocksJS-style pubsub event emit.
type EmitMessage struct {
Topic string
Payload json.RawMessage
}
func (emit *EmitMessage) UnmarshalJSON(data []byte) error {
msg := struct {
Emit []json.RawMessage `json:"emit"`
}{}
if err := json.Unmarshal(data, &msg); err != nil {
return err
}
if len(msg.Emit) == 0 {
return fmt.Errorf("missing emit fields")
}
if err := json.Unmarshal(msg.Emit[0], &emit.Topic); err != nil {
return err
}
if len(msg.Emit) > 1 {
emit.Payload = msg.Emit[1]
}
return nil
}
func (emit *EmitMessage) MarshalJSON() ([]byte, error) {
msg := struct {
Emit []json.RawMessage `json:"emit"`
}{}
if emit.Topic == "" {
return nil, fmt.Errorf("missing topic")
}
rawTopic, err := json.Marshal(emit.Topic)
if err != nil {
return nil, err
}
msg.Emit = append(msg.Emit, rawTopic)
if emit.Payload != nil {
msg.Emit = append(msg.Emit, emit.Payload)
}
return json.Marshal(msg)
}
func MarshalEmit(topic string, payload interface{}) ([]byte, error) {
emit := EmitMessage{
Topic: topic,
}
if payload != nil {
rawPayload, err := json.Marshal(payload)
if err != nil {
return nil, err
}
emit.Payload = rawPayload
}
return emit.MarshalJSON()
}