forked from StephanU/beats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
enc.go
137 lines (112 loc) · 2.42 KB
/
enc.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
package elasticsearch
import (
"bytes"
"compress/gzip"
"encoding/json"
"io"
"net/http"
)
type bodyEncoder interface {
bulkBodyEncoder
Reader() io.Reader
Marshal(doc interface{}) error
}
type bulkBodyEncoder interface {
bulkWriter
AddHeader(*http.Header)
Reset()
}
type bulkWriter interface {
Add(meta, obj interface{}) error
AddRaw(raw interface{}) error
}
type jsonEncoder struct {
buf *bytes.Buffer
}
type gzipEncoder struct {
buf *bytes.Buffer
gzip *gzip.Writer
}
func newJSONEncoder(buf *bytes.Buffer) *jsonEncoder {
if buf == nil {
buf = bytes.NewBuffer(nil)
}
return &jsonEncoder{buf}
}
func (b *jsonEncoder) Reset() {
b.buf.Reset()
}
func (b *jsonEncoder) AddHeader(header *http.Header) {
header.Add("Content-Type", "application/json; charset=UTF-8")
}
func (b *jsonEncoder) Reader() io.Reader {
return b.buf
}
func (b *jsonEncoder) Marshal(obj interface{}) error {
b.Reset()
enc := json.NewEncoder(b.buf)
return enc.Encode(obj)
}
func (b *jsonEncoder) AddRaw(raw interface{}) error {
enc := json.NewEncoder(b.buf)
return enc.Encode(raw)
}
func (b *jsonEncoder) Add(meta, obj interface{}) error {
enc := json.NewEncoder(b.buf)
pos := b.buf.Len()
if err := enc.Encode(meta); err != nil {
b.buf.Truncate(pos)
return err
}
if err := enc.Encode(obj); err != nil {
b.buf.Truncate(pos)
return err
}
return nil
}
func newGzipEncoder(level int, buf *bytes.Buffer) (*gzipEncoder, error) {
if buf == nil {
buf = bytes.NewBuffer(nil)
}
w, err := gzip.NewWriterLevel(buf, level)
if err != nil {
return nil, err
}
return &gzipEncoder{buf, w}, nil
}
func (b *gzipEncoder) Reset() {
b.buf.Reset()
b.gzip.Reset(b.buf)
}
func (b *gzipEncoder) Reader() io.Reader {
b.gzip.Close()
return b.buf
}
func (b *gzipEncoder) AddHeader(header *http.Header) {
header.Add("Content-Type", "application/json; charset=UTF-8")
header.Add("Content-Encoding", "gzip")
}
func (b *gzipEncoder) Marshal(obj interface{}) error {
b.Reset()
enc := json.NewEncoder(b.gzip)
err := enc.Encode(obj)
return err
}
func (b *gzipEncoder) AddRaw(raw interface{}) error {
enc := json.NewEncoder(b.gzip)
return enc.Encode(raw)
}
func (b *gzipEncoder) Add(meta, obj interface{}) error {
enc := json.NewEncoder(b.gzip)
pos := b.buf.Len()
if err := enc.Encode(meta); err != nil {
b.buf.Truncate(pos)
return err
}
if err := enc.Encode(obj); err != nil {
b.buf.Truncate(pos)
return err
}
b.gzip.Flush()
return nil
}