-
Notifications
You must be signed in to change notification settings - Fork 1
/
wsmsg.go
74 lines (67 loc) · 1.68 KB
/
wsmsg.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
package jaws
import (
"bytes"
"html"
"strconv"
"strings"
"github.com/linkdata/jaws/jid"
"github.com/linkdata/jaws/what"
)
// wsMsg is a message sent to or from a WebSocket.
type wsMsg struct {
Data string // data to send
Jid Jid // Jid to send, or negative to not send
What what.What // command
}
func (m *wsMsg) Append(b []byte) []byte {
b = append(b, m.What.String()...)
b = append(b, '\t')
if m.Jid >= 0 {
if m.Jid > 0 {
b = m.Jid.Append(b)
}
b = append(b, '\t')
b = strconv.AppendQuote(b, m.Data)
} else {
b = append(b, m.Data...)
}
b = append(b, '\n')
return b
}
func (m *wsMsg) Format() string {
return string(m.Append(nil))
}
// wsParse parses an incoming text buffer into a message.
func wsParse(txt []byte) (wsMsg, bool) {
if len(txt) > 2 && txt[len(txt)-1] == '\n' {
if nl1 := bytes.IndexByte(txt, '\t'); nl1 >= 0 {
if nl2 := bytes.IndexByte(txt[nl1+1:], '\t'); nl2 >= 0 {
nl2 += nl1 + 1
// What ... Jid ... Data ... EOL
// txt[0:nl1] ... txt[nl1+1 : nl2] ... txt[nl2+1:len(txt)-1] ... \n
if wht := what.Parse(string(txt[0:nl1])); wht.IsValid() {
if id := jid.ParseString(string(txt[nl1+1 : nl2])); id.IsValid() {
data := string(txt[nl2+1 : len(txt)-1])
if txt[nl2+1] == '"' {
var err error
if data, err = strconv.Unquote(data); err != nil {
return wsMsg{}, false
}
}
return wsMsg{
Data: strings.ToValidUTF8(data, ""),
Jid: id,
What: wht,
}, true
}
}
}
}
}
return wsMsg{}, false
}
func (m *wsMsg) FillAlert(err error) {
m.Jid = 0
m.What = what.Alert
m.Data = "danger\n" + html.EscapeString(err.Error())
}