-
Notifications
You must be signed in to change notification settings - Fork 0
/
yamls.go
83 lines (67 loc) · 1.46 KB
/
yamls.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
package utils
import (
"encoding/json"
"fmt"
"os"
k8Yaml "sigs.k8s.io/yaml"
"gopkg.in/yaml.v3"
)
func YamlToMap(filename string) (map[string]interface{}, error) {
yamlFile, err := os.ReadFile(string(filename))
if err != nil {
return nil, err
}
obj := make(map[string]interface{})
err = yaml.Unmarshal(yamlFile, &obj)
if err != nil {
return nil, err
}
return obj, nil
}
func YamlToList(filename string) ([]map[string]interface{}, error) {
yamlFile, err := os.ReadFile(filename)
if err != nil {
return nil, err
}
var obj []map[string]interface{}
err = yaml.Unmarshal(yamlFile, &obj)
if err != nil {
return nil, err
}
return obj, nil
}
func YamlToStruct[T any](filename string, obj *T) error {
yamlFile, err := os.ReadFile(filename)
if err != nil {
return err
}
err = yaml.Unmarshal(yamlFile, obj)
if err != nil {
return err
}
return nil
}
func StructToYaml(obj interface{}) ([]byte, error) {
yaml, err := yaml.Marshal(obj)
if err != nil {
fmt.Printf("Error while Marshaling %T: %v", obj, err)
return nil, err
}
return yaml, nil
}
func StructToYamlK8s(obj interface{}) ([]byte, error) {
yaml, err := k8Yaml.Marshal(obj)
if err != nil {
fmt.Printf("Error while Marshaling %T: %v", obj, err)
return nil, err
}
return yaml, nil
}
func StructToJson(obj interface{}) ([]byte, error) {
b, err := json.Marshal(obj)
if err != nil {
fmt.Printf("Error while Marshaling %T: %v\n", obj, err)
return nil, err
}
return b, nil
}