-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmsg.go
84 lines (67 loc) · 1.57 KB
/
msg.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
82
83
84
package webrpc
import "encoding/json"
// MessageType represents the kind of low-level message being received.
type MessageType int
// This is an enumeration of possible event types.
const (
Init MessageType = 0
Event MessageType = 1
Reply MessageType = 2
Ping MessageType = 3
Pong MessageType = 4
)
// Message represents a raw RPC message.
type Message struct {
Type MessageType `json:"type"`
Ack int `json:"ack,omitempty"`
Name string `json:"name,omitempty"`
Data []json.RawMessage `json:"data,omitempty"`
}
// NewEvent creates a new event message.
func NewEvent(name string, args ...interface{}) (Message, error) {
msg := Message{
Type: Event,
Name: name,
}
err := msg.SetData(args...)
if err != nil {
return Message{}, err
}
return msg, nil
}
// NewReply creates a new reply message.
func NewReply(ack int, name string, args ...interface{}) (Message, error) {
msg := Message{
Type: Reply,
Ack: ack,
Name: name,
}
err := msg.SetData(args...)
if err != nil {
return Message{}, err
}
return msg, nil
}
func newPing() Message {
return Message{Type: Ping}
}
func newPong() Message {
return Message{Type: Pong}
}
func newInit() Message {
return Message{Type: Init}
}
// SetData sets the data to the provided arguments, returning an error if the
// data could not be marshalled.
func (m *Message) SetData(args ...interface{}) error {
var err error
l := len(args)
m.Data = make([]json.RawMessage, l)
for i := 0; i < l; i++ {
m.Data[i], err = json.Marshal(args[i])
if err != nil {
return err
}
}
return nil
}