-
-
Notifications
You must be signed in to change notification settings - Fork 163
/
Copy pathread_config_file.go
83 lines (77 loc) · 1.92 KB
/
read_config_file.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 helper
import (
"encoding/json"
"fmt"
"os"
"strings"
"github.com/BurntSushi/toml"
"github.com/thomaspoignant/go-feature-flag/model/dto"
"gopkg.in/yaml.v3"
)
var ConfigFileDefaultLocations = []string{
"./",
"/goff/",
"/etc/opt/goff/",
}
func LoadConfigFile(
inputFilePath string,
configFormat string,
defaultLocations []string,
) (map[string]dto.DTO, error) {
filename := "flags.goff"
if defaultLocations == nil {
defaultLocations = ConfigFileDefaultLocations
}
supportedExtensions := []string{
"yaml",
"toml",
"json",
"yml",
}
if inputFilePath != "" {
if _, err := os.Stat(inputFilePath); err != nil {
return nil, fmt.Errorf("impossible to find config file %s", inputFilePath)
}
return readConfigFile(inputFilePath, configFormat)
}
for _, location := range defaultLocations {
for _, ext := range supportedExtensions {
configFile := fmt.Sprintf("%s%s.%s", location, filename, ext)
if _, err := os.Stat(configFile); err == nil {
return readConfigFile(configFile, ext)
}
}
}
return nil, fmt.Errorf(
"impossible to find config file in the default locations [%s]",
strings.Join(defaultLocations, ","),
)
}
func readConfigFile(configFile string, configFormat string) (map[string]dto.DTO, error) {
dat, err := os.ReadFile(configFile)
if err != nil {
return nil, err
}
var flags map[string]dto.DTO
switch strings.ToLower(configFormat) {
case "toml":
err := toml.Unmarshal(dat, &flags)
if err != nil {
return nil, fmt.Errorf("%s: could not parse file (toml): %w", configFile, err)
}
return flags, nil
case "json":
err := json.Unmarshal(dat, &flags)
if err != nil {
return nil, fmt.Errorf("%s: could not parse file (json): %w", configFile, err)
}
return flags, nil
default:
// default is YAML
err := yaml.Unmarshal(dat, &flags)
if err != nil {
return nil, fmt.Errorf("%s: could not parse file (yaml): %w", configFile, err)
}
return flags, nil
}
}