forked from go-stomp/stomp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
writer.go
100 lines (86 loc) · 1.94 KB
/
writer.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
package frame
import (
"bufio"
"io"
)
// slices used to write frames
var (
colonSlice = []byte{58} // colon ':'
crlfSlice = []byte{13, 10} // CR-LF
newlineSlice = []byte{10} // newline (LF)
nullSlice = []byte{0} // null character
)
// Writes STOMP frames to an underlying io.Writer.
type Writer struct {
writer *bufio.Writer
}
// Creates a new Writer object, which writes to an underlying io.Writer.
func NewWriter(writer io.Writer) *Writer {
return NewWriterSize(writer, 4096)
}
func NewWriterSize(writer io.Writer, bufferSize int) *Writer {
return &Writer{writer: bufio.NewWriterSize(writer, bufferSize)}
}
// Write the contents of a frame to the underlying io.Writer.
func (w *Writer) Write(f *Frame) error {
var err error
if f == nil {
// nil frame means send a heart-beat LF
_, err = w.writer.Write(newlineSlice)
if err != nil {
return err
}
} else {
_, err = w.writer.Write([]byte(f.Command))
if err != nil {
return err
}
_, err = w.writer.Write(newlineSlice)
if err != nil {
return err
}
//println("TX:", f.Command)
if f.Header != nil {
for i := 0; i < f.Header.Len(); i++ {
key, value := f.Header.GetAt(i)
//println(" ", key, ":", value)
_, err = replacerForEncodeValue.WriteString(w.writer, key)
if err != nil {
return err
}
_, err = w.writer.Write(colonSlice)
if err != nil {
return err
}
_, err = replacerForEncodeValue.WriteString(w.writer, value)
if err != nil {
return err
}
_, err = w.writer.Write(newlineSlice)
if err != nil {
return err
}
}
}
_, err = w.writer.Write(newlineSlice)
if err != nil {
return err
}
if len(f.Body) > 0 {
_, err = w.writer.Write(f.Body)
if err != nil {
return err
}
}
// write the final null (0) byte
_, err = w.writer.Write(nullSlice)
if err != nil {
return err
}
}
err = w.writer.Flush()
if err != nil {
return err
}
return nil
}