繁体   English   中英

读取配置文件时出错。 Golang 使用毒蛇 package

[英]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 package 读取 env.json 文件。

这是从 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"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM