读取配置文件时出错。 Golang 使用 viper 包

Error reading config file. Golang using viper package

我在读取 env.json 文件时需要帮助。任何时候我 运行 我的代码我总是得到这个错误

Error reading config file, Config File "env" Not Found in "[/Users/franklynomonade/go/src/bitbucket.org/core_backend/cmd/server/bitbucket.org/core_backend/pkg/app/config]"

"/Users/franklynomonade/go/src/bitbucket.org/core_backend/cmd/server"是我的main.go文件所在的路径,而"bitbucket.org/core_backend/pkg/app/config"是env.json文件所在的路径。 我相信应该读取 env.json 文件的路径是 "bitbucket.org/core_backend/pkg/app/config" 而不是 "/Users/franklynomonade/go/src/bitbucket.org/core_backend/cmd/server/bitbucket.org/core_backend/pkg/app/config"

我正在使用 github.com/spf13/viper 包来读取 env.json 文件。

func LoadConfig() {
    viper.AddConfigPath(myPath)

    viper.SetConfigName("env")

    viper.SetConfigType("json")

    // searches for config file in given paths and read it
    if err := viper.ReadInConfig(); err != nil {
        log.Fatalf("error reading config file: %s", err)
    }

    // confirm which config file is used
    log.Printf("Using s: %s\n", viper.ConfigFileUsed()
}

知道如何解决这个问题吗?

您可以使用相对路径或绝对路径,通常情况下,最好使用相对路径,因为您不需要在项目外部指定路径。

使用相对路径时,它会搜索相对于您执行二进制文件的文件夹的路径。

假设这是树:

├── core_backend
│   ├── cmd
│   └── pkg
│       ├── api 
│       └── app
│            └── config
│                  └── env.json

假设您 运行 您的程序在 core_backend 目录中,您会将变量 myPath 设置为此值

"pkg/app/config"