-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdump.go
105 lines (87 loc) · 1.89 KB
/
dump.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
package fluentbitconfig
import (
"bytes"
"encoding/json"
"errors"
"io"
"strings"
"gopkg.in/yaml.v3"
)
var ErrFormatUnknown = errors.New("format unknown")
type Format string
const (
FormatClassic = "classic"
FormatYAML = "yaml"
FormatJSON = "json"
)
func ParseAs(raw string, format Format) (Config, error) {
var out Config
switch strings.ToLower(string(format)) {
case "", "ini", "conf", "classic":
return ParseAsClassic(raw)
case "yml", "yaml":
return ParseAsYAML(raw)
case "json":
return ParseAsJSON(raw)
}
return out, ErrFormatUnknown
}
func ParseAsClassic(raw string) (Config, error) {
var out Config
return out, out.UnmarshalClassic([]byte(raw))
}
func ParseAsYAML(raw string) (Config, error) {
var out Config
dec := yaml.NewDecoder(strings.NewReader(raw))
dec.KnownFields(true)
err := dec.Decode(&out)
if errors.Is(err, io.EOF) {
return out, nil
}
return out, err
}
func ParseAsJSON(raw string) (Config, error) {
var out Config
dec := json.NewDecoder(strings.NewReader(raw))
dec.DisallowUnknownFields()
err := dec.Decode(&out)
if errors.Is(err, io.EOF) {
return out, nil
}
return out, err
}
func (c Config) DumpAs(format Format) (string, error) {
switch strings.ToLower(string(format)) {
case "", "ini", "conf", "classic":
return c.DumpAsClassic()
case "yml", "yaml":
return c.DumpAsYAML()
case "json":
return c.DumpAsJSON()
}
return "", ErrFormatUnknown
}
func (c Config) DumpAsClassic() (string, error) {
b, err := c.MarshalClassic()
if err != nil {
return "", err
}
return string(b), err
}
func (c Config) DumpAsYAML() (string, error) {
b, err := yaml.Marshal(c)
if err != nil {
return "", err
}
return string(b), nil
}
func (c Config) DumpAsJSON() (string, error) {
var buff bytes.Buffer
enc := json.NewEncoder(&buff)
enc.SetEscapeHTML(false)
err := enc.Encode(c)
if err != nil {
return "", err
}
return buff.String(), nil
}