package service import ( "fmt" "go_dreamfactory/cmd/v2/lib/common" "github.com/sirupsen/logrus" "github.com/spf13/viper" ) type ConfigService interface { GetConfig() *Config LoadConfig() error ApplyConfig() error } type ConfigServiceImpl struct { ResourcePath string Config *Config } type ServiceConf struct { SId int32 `yaml:"sid"` Name string `yaml:"name"` Url string `yaml:"url"` } type Services struct { Service *ServiceConf `yaml:"service"` } type Config struct { Services []*Services `yaml:"services"` } func NewConfigService() (ConfigService, error) { srv := &ConfigServiceImpl{ ResourcePath: common.DEFAULT_RESOURCE_PATH, Config: &Config{}, } err := srv.init() return srv, err } func (c *ConfigServiceImpl) LoadConfig() error { viper.AddConfigPath("./" + c.ResourcePath) return viper.ReadInConfig() } func (c *ConfigServiceImpl) ApplyConfig() error { if err := c.LoadConfig(); err != nil { logrus.Error(err) return err } if err := viper.Unmarshal(c.Config); err != nil { logrus.Error(err) return err } return nil } func (c *ConfigServiceImpl) Unmarshal() error { if sArr, ok := viper.Get("services").([]interface{}); ok { for _, service := range sArr { if services, ok := service.(map[interface{}]interface{}); ok { for _, v := range services { if vv, ok := v.(map[interface{}]interface{}); ok { for k, _ := range vv { kk := k.(string) logrus.Debug(vv[kk]) srvConf := &ServiceConf{} switch kk { case "sid": srvConf.SId = vv[kk].(int32) case "name": srvConf.Name = vv[kk].(string) case "url": srvConf.Url = vv[kk].(string) default: return fmt.Errorf("config key[%s] not foud", kk) } c.Config.Services = append(c.Config.Services, &Services{}) } } logrus.Debug(v) // if v } } } } return nil } func (c *ConfigServiceImpl) GetConfig() *Config { return c.Config } func (c *ConfigServiceImpl) init() error { viper.SetConfigName("config") viper.SetConfigType("yaml") return nil }