-
Notifications
You must be signed in to change notification settings - Fork 297
/
file_utils.go
54 lines (46 loc) · 1.13 KB
/
file_utils.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
package utils
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"github.com/rs/zerolog/log"
"gopkg.in/yaml.v3"
)
func convert(m map[interface{}]interface{}) map[string]interface{} {
res := map[string]interface{}{}
for k, v := range m {
switch v2 := v.(type) {
case map[interface{}]interface{}:
res[fmt.Sprint(k)] = convert(v2)
default:
res[fmt.Sprint(k)] = v
}
}
return res
}
func readFile(filePath string) (map[string]interface{}, error) {
var result map[string]interface{}
content, err := os.ReadFile(filePath)
if err != nil {
log.Trace().Msgf("failed to read %s", filePath)
return nil, err
}
fileExtension := filepath.Ext(filePath)
if fileExtension == ".json" {
err := json.Unmarshal(content, &result)
if err != nil {
log.Error().Msgf("Failed to unmarshal '%s'", filePath)
return nil, err
}
} else if fileExtension == ".yaml" || fileExtension == ".yml" {
var resultYaml map[interface{}]interface{}
err := yaml.Unmarshal(content, &resultYaml)
if err != nil {
log.Error().Msgf("Failed to unmarshal '%s'", filePath)
return nil, err
}
result = convert(resultYaml)
}
return result, nil
}