douqie1852 2018-10-21 14:32
浏览 34
已采纳

从执行的bin中读取配置

Im using go viper to read config file in my repo

myrepo
 -config.yaml
 -main.go

I use the following code

viper.SetConfigName("config")
viper.AddConfigPath(".")
viper.SetConfigType("yaml")
err := viper.ReadInConfig()

And now I compile it to binary and now im running it from diffrent path (run the bin) and I got error that the config not found, what could be wrong here ?

The file is there and If I use ioutil.ReadFile in debug I get it but not from the executable...

  • 写回答

1条回答 默认 最新

  • dpcnm2132 2018-10-21 16:14
    关注

    So you told viper that it can read the config from the location ./config.yaml. When you compile the project, the compiler does not compile the configuration data inside config.yaml with the binary. Hence, every time the binary runs, it looks for a file ./config.yaml.

    So you have few options here. Either you move the config file with the binary and make sure when you copy the binary, you copy the config as well. Another option you have is to have a flag "configpath" that you pass the config path to and viper should read that flag and fetch the configs. Another option is to put the config inside your .go file and that way the config is compiled (but I am guessing this is something you don't want)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?