小编xN0*_*31x的帖子

使用 viper 从 envfile 读取配置

我不太明白 viper 是如何工作的。这是我的代码:

配置.go

var Config *Configuration

type ServerConfiguration struct {
    Port string
}

type Configuration struct {
    Server   ServerConfiguration
}

func Init() {
    var configuration *Configuration
    viper.SetConfigFile(".env")
    viper.AutomaticEnv()
    if err := viper.ReadInConfig(); err != nil {
        log.Fatalf("Error reading config file, %s", err)
    }

    err := viper.Unmarshal(&configuration)
    if err != nil {
        log.Fatalf("Unable to decode into struct, %v", err)
    }

    Config = configuration
}

func GetConfig() *Configuration {
    return Config
}
Run Code Online (Sandbox Code Playgroud)

.env SERVER_PORT=:4747

问题是 Unmarshal 不起作用当我使用例如配置时。Server.Port 它是空的

go viper-go

6
推荐指数
1
解决办法
5526
查看次数

标签 统计

go ×1

viper-go ×1