forked from vjeantet/bitfan
-
Notifications
You must be signed in to change notification settings - Fork 0
/
encoder.go
82 lines (67 loc) · 1.85 KB
/
encoder.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
//go:generate bitfanDoc -codec encoder
// doc codec
package linecodec
import (
"bytes"
"io"
"text/template"
"github.com/awillis/bitfan/commons"
"github.com/mitchellh/mapstructure"
)
// doc encoder
type encoder struct {
w io.Writer
options encoderOptions
formatTpl *template.Template
log commons.Logger
}
// doc encoderOptions
type encoderOptions struct {
// Change the delimiter that separates lines
// @Default "\\n"
Delimiter string
// Format as a golang text/template
// @Default "{{TS "dd/MM/yyyy:HH:mm:ss" .}} {{.host}} {{.message}}"
Format string `mapstructure:"format"`
// You can set variable to be used in Statements by using ${var}.
// each reference will be replaced by the value of the variable found in Statement's content
// The replacement is case-sensitive.
// @ExampleLS var => {"hostname"=>"myhost","varname"=>"varvalue"}
Var map[string]string `mapstructure:"var"`
}
func NewEncoder(w io.Writer) *encoder {
e := &encoder{
w: w,
options: encoderOptions{
Delimiter: "\n",
Format: `{{ TS "dd/MM/yyyy:HH:mm:ss" . }} {{.host}} {{.message}}`,
},
}
loc, _ := commons.NewLocation(e.options.Format, "")
e.formatTpl, _, _ = loc.TemplateWithOptions(e.options.Var)
return e
}
func (e *encoder) SetOptions(conf map[string]interface{}, logger commons.Logger, cwl string) error {
e.log = logger
if err := mapstructure.Decode(conf, &e.options); err != nil {
return err
}
if e.options.Format != "" {
loc, err := commons.NewLocation(e.options.Format, cwl)
if err != nil {
return err
}
e.formatTpl, _, err = loc.TemplateWithOptions(e.options.Var)
if err != nil {
return err
}
}
return nil
}
func (e *encoder) Encode(data map[string]interface{}) error {
buff := bytes.NewBufferString("")
e.formatTpl.Execute(buff, data)
e.w.Write(buff.Bytes())
e.w.Write([]byte(e.options.Delimiter))
return nil
}