MCPcopy Create free account
hub / github.com/go-dev-frame/sponge / Parse

Function Parse

pkg/conf/parse.go:19–54  ·  view source on GitHub ↗

Parse configuration files to struct, including yaml, toml, json, etc., and turn on listening for configuration file changes if fs is not empty

(configFile string, obj interface{}, reloads ...func())

Source from the content-addressed store, hash-verified

17
18// Parse configuration files to struct, including yaml, toml, json, etc., and turn on listening for configuration file changes if fs is not empty
19func Parse(configFile string, obj interface{}, reloads ...func()) error {
20 v := reflect.ValueOf(obj)
21 if v.Kind() != reflect.Ptr || v.IsNil() {
22 return fmt.Errorf("obj must be a non-nil pointer")
23 }
24
25 confFileAbs, err := filepath.Abs(configFile)
26 if err != nil {
27 return err
28 }
29
30 filePathStr, filename := filepath.Split(confFileAbs)
31 ext := strings.TrimLeft(path.Ext(filename), ".")
32 if ext != "toml" {
33 filename = strings.ReplaceAll(filename, "."+ext, "") // excluding suffix names
34 }
35
36 viper.AddConfigPath(filePathStr) // path
37 viper.SetConfigName(filename) // file name
38 viper.SetConfigType(ext) // get the configuration type from the file name
39 err = viper.ReadInConfig()
40 if err != nil {
41 return err
42 }
43
44 err = viper.Unmarshal(obj)
45 if err != nil {
46 return err
47 }
48
49 if len(reloads) > 0 {
50 watchConfig(obj, reloads...)
51 }
52
53 return nil
54}
55
56// ParseConfigData parse data to struct, parameter format is the configuration file format, such as "yaml", "json", "toml"
57func ParseConfigData(data []byte, format string, obj interface{}) error {

Callers 5

InitFunction · 0.92
NewCenterFunction · 0.92
PerfTestAgentCMDFunction · 0.92
TestParseFunction · 0.85
TestParseErrFunction · 0.85

Calls 3

watchConfigFunction · 0.85
ErrorfMethod · 0.80
UnmarshalMethod · 0.65

Tested by 2

TestParseFunction · 0.68
TestParseErrFunction · 0.68