...
1
16
17 package encoder
18
19 import (
20 `encoding/json`
21 `io`
22 )
23
24
25 type StreamEncoder struct {
26 w io.Writer
27 Encoder
28 }
29
30
31
32
33 func NewStreamEncoder(w io.Writer) *StreamEncoder {
34 return &StreamEncoder{w: w}
35 }
36
37
38 func (enc *StreamEncoder) Encode(val interface{}) (err error) {
39 buf := newBytes()
40 out := buf
41
42
43 err = EncodeInto(&out, val, enc.Opts)
44 if err != nil {
45 goto free_bytes
46 }
47
48 if enc.indent != "" || enc.prefix != "" {
49
50 buf := newBuffer()
51 err = json.Indent(buf, out, enc.prefix, enc.indent)
52 if err != nil {
53 freeBuffer(buf)
54 goto free_bytes
55 }
56
57
58 if enc.Opts & NoEncoderNewline == 0 {
59 buf.WriteByte('\n')
60 }
61
62
63 _, err = io.Copy(enc.w, buf)
64 if err != nil {
65 freeBuffer(buf)
66 goto free_bytes
67 }
68
69 } else {
70
71 var n int
72 for len(out) > 0 {
73 n, err = enc.w.Write(out)
74 out = out[n:]
75 if err != nil {
76 goto free_bytes
77 }
78 }
79
80
81 if enc.Opts & NoEncoderNewline == 0 {
82 enc.w.Write([]byte{'\n'})
83 }
84 }
85
86 free_bytes:
87 freeBytes(buf)
88 return err
89 }
90
View as plain text