关于如何使用 vpier 读取配置文件绑定到 struct 的疑问
1. 问题描述:
- 如何将 viper 读取到 yaml 配置文件反序列化绑定到 Config 结构体中
- 是否建议使用反序列化绑定到结构体的做法,或者是建议使用 Code1.1 直接读取返回的方式更佳
- 能否指点读取代码优化,Code1.1 中的 ParseConfig 函数的返回值感觉写的不理想
- 查阅了很多资料,试着使用 viper.Unmarshal() 进行反序列化操作时并没有得到想要的值,且控制台打印空,也无报错
- 反序列化是否需要使用 tag 绑定结构体如 Code1.2
- config.yaml 配置文件如 Code1.3
2. Code:
1.1
func main() {
config, err := tool.ParseConfig("./config/app.yaml")
if err != nil {
log.Println(err, "===================")
}
fmt.Println(config.GetString("config.AppHost")) // localhost
}
func ParseConfig(path string) (vipers *viper.Viper, err error) {
v := viper.New() // 实例化 viper 对象
v.SetConfigFile(path) // 设置配置文件路径
if err := v.ReadInConfig(); err != nil { // 读取配置文件
log.Println("read in config failed", err)
}
return v, nil
1.2
type Config struct {
AppHost string `yaml:"AppHost"`
AppPort int `yaml:"AppPort"`
}
1.3
config:
AppName: Test
AppHost: localhost
AppPort: 80
结构体这么写
global.Config 是Config 结构体。这个结构体太长了就不贴出来了。