123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- // Copyright 2019 getensh.com. All rights reserved.
- // Use of this source code is governed by getensh.com.
- package parser
- import (
- "fmt"
- "path/filepath"
- "strings"
- "property-household/config"
- "github.com/fsnotify/fsnotify"
- "github.com/spf13/viper"
- )
- var v *viper.Viper
- var Conf *config.Configure
- // LoadConfig 装载配置文件
- func LoadConfig(filename string) error {
- configPath, configName := filepath.Split(filename)
- fileList := strings.Split(configName, ".")
- if len(fileList) < 2 {
- return fmt.Errorf("%s", "文件格式不正确")
- }
- configName = fileList[0]
- fileExt := fileList[1]
- var err error
- if fileExt == "json" {
- err = LoadConfigFromJson(configName, configPath)
- } else if fileExt == "yaml" || fileExt == "yml" {
- err = LoadConfigFromYaml(configName, configPath)
- } else {
- err = fmt.Errorf("%s", "不支持的文件格式")
- }
- // 出错直接返回
- if err != nil {
- return err
- }
- // 设置文件监听函数
- v.OnConfigChange(func(e fsnotify.Event) {
- fmt.Printf("配置文件有变化, Event:%s \n", e.String())
- parseConfig()
- Handle()
- })
- // 监听
- v.WatchConfig()
- return nil
- }
- // LoadConfigFromYaml 装载yaml类型的配置文件
- func LoadConfigFromYaml(configName, configPath string) error {
- v = viper.New()
- v.SetConfigName(configName)
- v.AddConfigPath(configPath)
- //设置配置文件类型
- v.SetConfigType("yaml")
- if err := v.ReadInConfig(); err != nil {
- return err
- }
- return parseConfig()
- }
- // LoadConfigFromJson 装载json类型的配置文件
- func LoadConfigFromJson(configName, configPath string) error {
- v = viper.New()
- v.SetConfigName(configName)
- v.AddConfigPath(configPath)
- //设置配置文件类型
- v.SetConfigType("json")
- if err := v.ReadInConfig(); err != nil {
- return err
- }
- return parseConfig()
- }
- func parseConfig() error {
- Conf = &config.Configure{}
- if err := v.Unmarshal(Conf); err != nil {
- return err
- }
- return nil
- }
|