-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjson_writer.go
53 lines (41 loc) · 1.18 KB
/
json_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
package ratchet_processors
import (
"io"
"github.com/licaonfee/ratchet/data"
"github.com/licaonfee/ratchet/processors"
"github.com/licaonfee/ratchet/util"
)
type JSONWriter struct {
writer io.Writer
buffer []data.JSON
}
// Assert JSONWriter satisfies the interface processors.DataProcessor
var _ processors.DataProcessor = &JSONWriter{}
// NewJSONWriter returns a new JSONWriter wrapping the given io.Writer object
func NewJSONWriter(w io.Writer) *JSONWriter {
return &JSONWriter{
writer: w,
buffer: make([]data.JSON, 0),
}
}
func (w *JSONWriter) ProcessData(d data.JSON, outputChan chan data.JSON, killChan chan error) {
w.buffer = append(w.buffer, d)
}
func (w *JSONWriter) Finish(outputChan chan data.JSON, killChan chan error) {
_, err := w.writer.Write([]byte("["))
util.KillPipelineIfErr(err, killChan)
last := len(w.buffer) - 1
for i, d := range w.buffer {
_, err = w.writer.Write(d)
util.KillPipelineIfErr(err, killChan)
if i != last {
_, err = w.writer.Write([]byte(","))
}
util.KillPipelineIfErr(err, killChan)
}
_, err = w.writer.Write([]byte("]"))
util.KillPipelineIfErr(err, killChan)
}
func (w *JSONWriter) String() string {
return "JSONWriter"
}