简体   繁体   English

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

[英]Error reading config file. Golang using viper package

please i need help in reading from an env.json file.我需要帮助阅读 env.json 文件。 Anytime i run my code i always get this error任何时候我运行我的代码我总是得到这个错误

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" is the path where my main.go file is in, while "bitbucket.org/core_backend/pkg/app/config" is the path where the env.json file is located. "/Users/franklynomonade/go/src/bitbucket.org/core_backend/cmd/server"是我的 main.go 文件所在的路径,而"bitbucket.org/core_backend/pkg/app/config"是其中的路径env.json 文件位于。 I believe the path where the env.json file should be read is "bitbucket.org/core_backend/pkg/app/config" and not "/Users/franklynomonade/go/src/bitbucket.org/core_backend/cmd/server/bitbucket.org/core_backend/pkg/app/config"我相信应该读取 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"

I am using github.com/spf13/viper package to read the env.json file.我正在使用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()
}

Any idea on how i can fix this?关于如何解决这个问题的任何想法?

You can use relative or absolute paths, usually, it's better to use relative paths since you don't need to specify the path outside of your project.您可以使用相对路径或绝对路径,通常,最好使用相对路径,因为您不需要在项目外部指定路径。

When using the relative path, it searches the path relative to the folder in which you executed the binary.使用相对路径时,它会搜索相对于执行二进制文件的文件夹的路径。

Assuming this is the tree:假设这是树:

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

Let's say you run your program in the core_backend directory, you would set your variable myPath to this value假设您在core_backend目录中运行程序,您会将变量myPath设置为此值

"pkg/app/config"

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

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