我在 Golang 中使用 Viper 从环境变量加载配置值。但是,如果未设置所需的环境变量,我希望 viper.Unmarshal 返回错误。
默认情况下,如果缺少环境变量,viper.Unmarshal 不会失败 - 它只是将零值分配给结构字段。
这是我的代码:
package main
import (
"fmt"
"log"
"github.com/spf13/viper"
)
type Config struct {
DatabaseURL string `mapstructure:"DATABASE_URL"`
}
func main() {
viper.AutomaticEnv()
var config Config
if err := viper.Unmarshal(&config); err != nil {
log.Fatalf("Error unmarshaling config: %v", err)
}
fmt.Println("Config:", config)
}
如果没有设置DATABASE_URL,config.DatabaseURL只是一个空字符串,而不会导致错误。
我尝试使用 viper.BindEnv("DATABASE_URL"),但是当 DATABASE_URL 丢失时 Unmarshal 仍然不会失败。
在 Viper 中,Unmarshal 函数通过 DecoderConfigOption 接受钩子。查看 viper,我发现 DecoderConfig 结构体有一个 ErrorUnset 字段:
// If ErrorUnset is true, then it is an error for there to exist
// fields in the result that were not set in the decoding process
// (extra fields). This only applies to decoding to a struct. This
// will affect all nested structs as well.
ErrorUnset bool
但是,我不确定如何正确地将此配置作为 Unmarshal 中的钩子传递。如果有人知道如何使用 DecoderConfigOption 启用 ErrorUnset,谢谢!
如果未设置所需的环境变量,如何让 viper.Unmarshal DecodeHook 返回错误?