-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathencoder.go
executable file
·89 lines (81 loc) · 1.59 KB
/
encoder.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
package client
import (
"encoding/json"
"fmt"
"io"
"github.com/webrtcn/go-socketio-client/parser"
)
type encoder struct {
w parser.FrameWriter
err error
}
func newEncoder(w parser.FrameWriter) *encoder {
return &encoder{
w: w,
}
}
func (e *encoder) Encode(v packet) error {
attachments := encodeAttachments(v.Data)
v.attachNumber = len(attachments)
if v.attachNumber > 0 {
v.Type += _BINARY_EVENT - _EVENT
}
if err := e.encodePacket(v); err != nil {
return err
}
for _, a := range attachments {
if err := e.writeBinary(a); err != nil {
return err
}
}
return nil
}
func (e *encoder) encodePacket(v packet) error {
writer, err := e.w.NextWriter(parser.MessageText)
if err != nil {
return err
}
defer writer.Close()
w := newTrimWriter(writer, "\n")
wh := newWriterHelper(w)
wh.Write([]byte{byte(v.Type) + '0'})
if v.Type == _BINARY_EVENT || v.Type == _BINARY_ACK {
wh.Write([]byte(fmt.Sprintf("%d-", v.attachNumber)))
}
needEnd := false
if v.NSP != "" {
wh.Write([]byte(v.NSP))
needEnd = true
}
if v.Id >= 0 {
f := "%d"
if needEnd {
f = ",%d"
needEnd = false
}
wh.Write([]byte(fmt.Sprintf(f, v.Id)))
}
if v.Data != nil {
if needEnd {
wh.Write([]byte{','})
needEnd = false
}
if wh.Error() != nil {
return wh.Error()
}
encoder := json.NewEncoder(w)
return encoder.Encode(v.Data)
}
return wh.Error()
}
func (e *encoder) writeBinary(r io.Reader) error {
writer, err := e.w.NextWriter(parser.MessageBinary)
if err != nil {
return err
}
defer writer.Close()
if _, err := io.Copy(writer, r); err != nil {
return err
}
return nil
}