forked from miracl/conflate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
marshal.go
110 lines (85 loc) · 2.27 KB
/
marshal.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
package conflate
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"github.com/BurntSushi/toml"
"github.com/ghodss/yaml"
)
var errToml = errors.New("the data could not be marshalled to toml")
func jsonMarshalAll(data ...interface{}) ([][]byte, error) {
var outs [][]byte
for i, datum := range data {
out, err := jsonMarshal(datum)
if err != nil {
return nil, fmt.Errorf("could not marshal data %v: %w", i, err)
}
outs = append(outs, out)
}
return outs, nil
}
func jsonMarshalUnmarshal(in, out interface{}) error {
data, err := jsonMarshal(in)
if err != nil {
return err
}
return JSONUnmarshal(data, out)
}
// JSONUnmarshal unmarshals the data as JSON.
func JSONUnmarshal(data []byte, out interface{}) error {
err := json.Unmarshal(data, out)
if err != nil {
return fmt.Errorf("the data could not be unmarshalled as json: %w", err)
}
return nil
}
// YAMLUnmarshal unmarshals the data as YAML.
func YAMLUnmarshal(data []byte, out interface{}) error {
err := yaml.Unmarshal(data, out)
if err != nil {
return fmt.Errorf("the data could not be unmarshalled as yaml: %w", err)
}
return nil
}
// TOMLUnmarshal unmarshals the data as TOML.
func TOMLUnmarshal(data []byte, out interface{}) error {
err := toml.Unmarshal(data, out)
if err != nil {
return fmt.Errorf("the data could not be unmarshalled as toml: %w", err)
}
return nil
}
func jsonMarshal(data interface{}) ([]byte, error) {
buffer := bytes.Buffer{}
encoder := json.NewEncoder(&buffer)
encoder.SetEscapeHTML(false)
encoder.SetIndent("", " ")
err := encoder.Encode(data)
if err != nil {
return nil, fmt.Errorf("the data could not be marshalled to json: %w", err)
}
return buffer.Bytes(), nil
}
func yamlMarshal(in interface{}) ([]byte, error) {
data, err := yaml.Marshal(in)
if err != nil {
return nil, fmt.Errorf("the data could not be marshalled to yaml: %w", err)
}
return data, nil
}
func tomlMarshal(in interface{}) (out []byte, err error) {
defer func() {
if isPanicking := recover(); isPanicking != nil {
err = fmt.Errorf("%w : %v", errToml, isPanicking)
}
}()
buf := bytes.Buffer{}
enc := toml.NewEncoder(&buf)
err = enc.Encode(in)
if err != nil {
return nil, fmt.Errorf("the data could not be marshalled to toml: %w", err)
}
out = buf.Bytes()
return out, nil
}