-
Notifications
You must be signed in to change notification settings - Fork 0
/
protocol.go
100 lines (81 loc) · 2.07 KB
/
protocol.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package webchan
const SERVER_IDENT = "WEBCHAN"
const (
WELCOME = 0
SUBSCRIBE = 5
UNSUBSCRIBE = 6
PUBLISH = 7
EVENT = 8
)
type ProtocolError struct{
Msg string
}
func (self *ProtocolError) Error() string {
return "webchan:" + self.Msg
}
var ErrInvalidNumArgs = &ProtocolError{ "invalid number of argument" }
type WelcomeMsg struct {
SessionId string
ProtocalVersion string
ServerIdent string
}
func (self *WelcomeMsg)Marshal(sessionId string) ([]byte,error){
data := [...]interface{}{WELCOME,sessionId,"1",SERVER_IDENT}
b,err := json.Marshal(data)
return b,err
}
type SubscribeMsg struct {
Channel string
}
func (self *SubscribeMsg)UnmarshalJSON(data []interface{}) error {
if len(data) != 2 {
return ErrInvalidNumArgs
}
var ok bool
if self.Channel,ok = data[1].(string); !ok {
return &ProtocolError{"invalid channel"}
}
return nil
}
type UnsubscribeMsg struct{
Channel string
}
func (self *UnsubcribeMsg)UnmarshalJSON(data []interface{}) error {
if len(data) != 2 {
return ErrInvalidNumArgs
}
var ok bool
if self.Channel,ok = data[1].(string); !ok {
return &ProtocalError{"invalid channel"}
}
return nil
}
type PublishMsg struct {
Channel string
Event string
Data interface{}
}
func (self *PublishMsg)UnmarshalJSON(data []interface{}) error {
if len(data) != 4 {
return ErrInvalidNumArgs
}
var ok bool
if self.Channel,ok = data[1].(string); !ok {
return &ProtocolError{"invalid channel"}
}
if self.Event,ok = data[2].(string); !ok {
return &ProtocolError{"invalid event"}
}
self.Data = data[3]
return nil
}
type EventMsg struct {
Channel string
Event string
Data interface{}
}
func (self *EventMsg)Marshal() ([]byte,error){
data := []interface{}{EVENT,self.Channel,self.Event,self.Data}
b,err := json.Marshal(data)
return b,err
}