-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathpackets.go
143 lines (118 loc) · 2.36 KB
/
packets.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
package yagnats
import (
"encoding/json"
"fmt"
)
type Packet interface {
Encode() []byte
}
type PingPacket struct{}
func (p *PingPacket) Encode() []byte {
return []byte("PING\r\n")
}
type PongPacket struct{}
func (p *PongPacket) Encode() []byte {
return []byte("PONG\r\n")
}
type InfoPacket struct {
Payload string
}
func (p *InfoPacket) Encode() []byte {
return []byte(fmt.Sprintf("INFO %s\r\n", p.Payload))
}
type ConnectPacket struct {
User string
Pass string
}
type connectionPayload struct {
User string `json:"user"`
Pass string `json:"pass"`
Verbose bool `json:"verbose"`
Pedantic bool `json:"pedantic"`
}
func (p *ConnectPacket) Encode() []byte {
payload := connectionPayload{
Verbose: true,
Pedantic: true,
User: p.User,
Pass: p.Pass,
}
json, err := json.Marshal(payload)
if err != nil {
panic("invalid JSON connect payload")
}
return []byte(fmt.Sprintf("CONNECT %s\r\n", json))
}
type OKPacket struct{}
func (p *OKPacket) Encode() []byte {
return []byte("+OK\r\n")
}
type ERRPacket struct {
Message string
}
func (p *ERRPacket) Encode() []byte {
return []byte(fmt.Sprintf("-ERR '%s'\r\n", p.Message))
}
type SubPacket struct {
Subject string
Queue string
ID int64
}
func (p *SubPacket) Encode() []byte {
if p.Queue != "" {
return []byte(fmt.Sprintf("SUB %s %s %d\r\n", p.Subject, p.Queue, p.ID))
} else {
return []byte(fmt.Sprintf("SUB %s %d\r\n", p.Subject, p.ID))
}
}
type UnsubPacket struct {
ID int64
}
func (p *UnsubPacket) Encode() []byte {
return []byte(fmt.Sprintf("UNSUB %d\r\n", p.ID))
}
type PubPacket struct {
Subject string
ReplyTo string
Payload []byte
}
func (p *PubPacket) Encode() []byte {
if p.ReplyTo != "" {
return []byte(
fmt.Sprintf(
"PUB %s %s %d\r\n%s\r\n",
p.Subject, p.ReplyTo, len(p.Payload), p.Payload,
),
)
} else {
return []byte(
fmt.Sprintf(
"PUB %s %d\r\n%s\r\n",
p.Subject, len(p.Payload), p.Payload,
),
)
}
}
type MsgPacket struct {
Subject string
SubID int64
ReplyTo string
Payload []byte
}
func (p *MsgPacket) Encode() []byte {
if p.ReplyTo != "" {
return []byte(
fmt.Sprintf(
"MSG %s %d %s %d\r\n%s\r\n",
p.Subject, p.SubID, p.ReplyTo, len(p.Payload), p.Payload,
),
)
} else {
return []byte(
fmt.Sprintf(
"MSG %s %d %d\r\n%s\r\n",
p.Subject, p.SubID, len(p.Payload), p.Payload,
),
)
}
}