-
Notifications
You must be signed in to change notification settings - Fork 3
/
serializer.go
123 lines (94 loc) · 2.28 KB
/
serializer.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
package goldga
import (
"encoding/json"
"fmt"
"io"
"github.com/BurntSushi/toml"
"github.com/davecgh/go-spew/spew"
yaml "gopkg.in/yaml.v2"
)
// nolint: gochecknoglobals
var (
DefaultSerializer Serializer = &DumpSerializer{
Config: newDefaultDumpConfig(),
}
)
type Serializer interface {
Serialize(w io.Writer, input interface{}) error
}
type DumpSerializer struct {
Config *spew.ConfigState
}
func (d *DumpSerializer) Serialize(w io.Writer, input interface{}) error {
d.Config.Fdump(w, input)
return nil
}
func newDefaultDumpConfig() *spew.ConfigState {
conf := spew.NewDefaultConfig()
conf.SortKeys = true
conf.DisableCapacities = true
conf.DisablePointerAddresses = true
conf.DisablePointerMethods = true
return conf
}
type YAMLSerializer struct{}
func (y *YAMLSerializer) Serialize(w io.Writer, input interface{}) error {
enc := yaml.NewEncoder(w)
defer enc.Close()
if err := enc.Encode(input); err != nil {
return fmt.Errorf("yaml encode error: %w", err)
}
return nil
}
type JSONSerializer struct {
EscapeHTML bool
IndentPrefix string
Indent string
}
func (j *JSONSerializer) Serialize(w io.Writer, input interface{}) error {
enc := json.NewEncoder(w)
enc.SetEscapeHTML(j.EscapeHTML)
enc.SetIndent(j.IndentPrefix, j.Indent)
if err := enc.Encode(input); err != nil {
return fmt.Errorf("json encode error: %w", err)
}
return nil
}
type TOMLSerializer struct {
Indent string
}
func (t *TOMLSerializer) Serialize(w io.Writer, input interface{}) error {
enc := toml.NewEncoder(w)
enc.Indent = t.Indent
if err := enc.Encode(input); err != nil {
return fmt.Errorf("toml encode error: %w", err)
}
return nil
}
type StringSerializer struct {
FallbackSerializer Serializer
}
func (s *StringSerializer) Serialize(w io.Writer, input interface{}) error {
var buf []byte
switch input := input.(type) {
case string:
buf = []byte(input)
case []byte:
buf = input
case fmt.Stringer:
buf = []byte(input.String())
default:
fallback := s.FallbackSerializer
if fallback == nil {
fallback = DefaultSerializer
}
if err := fallback.Serialize(w, input); err != nil {
return fmt.Errorf("fallback serialize error: %w", err)
}
return nil
}
if _, err := w.Write(buf); err != nil {
return fmt.Errorf("write error: %w", err)
}
return nil
}