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())
| 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 |
| 19 | func 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" |
| 57 | func ParseConfigData(data []byte, format string, obj interface{}) error { |