forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
json.go
89 lines (73 loc) · 1.72 KB
/
json.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 json
import (
"bytes"
stdjson "encoding/json"
"github.com/urso/go-structform/gotype"
"github.com/urso/go-structform/json"
"github.com/elastic/beats/libbeat/beat"
"github.com/elastic/beats/libbeat/common"
"github.com/elastic/beats/libbeat/outputs/codec"
)
// Encoder for serializing a beat.Event to json.
type Encoder struct {
buf bytes.Buffer
folder *gotype.Iterator
pretty bool
version string
}
type config struct {
Pretty bool
}
var defaultConfig = config{
Pretty: false,
}
func init() {
codec.RegisterType("json", func(info beat.Info, cfg *common.Config) (codec.Codec, error) {
config := defaultConfig
if cfg != nil {
if err := cfg.Unpack(&config); err != nil {
return nil, err
}
}
return New(config.Pretty, info.Version), nil
})
}
// New creates a new json Encoder.
func New(pretty bool, version string) *Encoder {
e := &Encoder{pretty: pretty, version: version}
e.reset()
return e
}
func (e *Encoder) reset() {
visitor := json.NewVisitor(&e.buf)
var err error
// create new encoder with custom time.Time encoding
e.folder, err = gotype.NewIterator(visitor,
gotype.Folders(
codec.MakeTimestampEncoder(),
codec.MakeBCTimestampEncoder(),
),
)
if err != nil {
panic(err)
}
}
// Encode serializies a beat event to JSON. It adds additional metadata in the
// `@metadata` namespace.
func (e *Encoder) Encode(index string, event *beat.Event) ([]byte, error) {
e.buf.Reset()
err := e.folder.Fold(makeEvent(index, e.version, event))
if err != nil {
e.reset()
return nil, err
}
json := e.buf.Bytes()
if !e.pretty {
return json, nil
}
var buf bytes.Buffer
if err = stdjson.Indent(&buf, json, "", " "); err != nil {
return nil, err
}
return buf.Bytes(), nil
}