I need to read data first of all from the fields inside the service, and only then look at the external fields.个
存在此类型的配置:
auth_service:
log_level: debug
port: 9999
mail_service:
log_level: debug
port: 9998
smtp:
host: localhost
port: 1025
username: ""
password: ""
email_from: "mailservice@test.test"
retries_count: 5
log_level: test
我试图通过viper.RegisterAlias("log_level", "auth_service.log_level")
来实现,但在这种形式下,外部字段是不能读取的.
获取配置的代码如下:
type Config struct {
LogLevel string `mapstructure:"log_level"`
Port int `mapstructure:"port"`
SMTP SMTPConfig `mapstructure:"smtp"`
}
type SMTPConfig struct {
Host string `mapstructure:"host"`
Port int `mapstructure:"port"`
Username string `mapstructure:"username"`
Password string `mapstructure:"password"`
EmailFrom string `mapstructure:"email_from"`
RetriesCount int `mapstructure:"retries_count"`
}
func LoadConfig(path string) (*Config, error) {
type ServiceConfig struct {
Cfg Config `mapstructure:"auth_service"`
}
viper.RegisterAlias("log_level","auth_service.log_level")
viper.AutomaticEnv()
if path != "" {
dir := p.Dir(path)
file := p.Base(path)
fileParts := strings.Split(file, ".")
if len(fileParts) != 2 {
return nil, fmt.Errorf("incorrect config file: %s", file)
}
viper.AddConfigPath(dir)
viper.SetConfigName(fileParts[0])
viper.SetConfigType(fileParts[1])
err := viper.ReadInConfig()
if err != nil {
return nil, err
}
}
fmt.Println(viper.AllKeys())
var config ServiceConfig
err := viper.Unmarshal(&config)
if err != nil {
return nil, err
}
return &config.Cfg, nil
}
需要ServiceConfig,这样您才能从SERVICE_NAME_FIELD_NAME获得值,因为mapstructure:"service_name.field"
不起作用.