Search code examples
gobin

Read config from executed 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...


Solution

  • 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)