Access Config in Subcommands

(Ryan Quinn) #1

I’m working with Cobra and Viper to create a little command line program, and I’m trying to figure out how to access the config file Viper reads in subcommands. Right now, I’m marshalling the YAML config into a global struct, which works, but I’m wondering if there is a better way to access the config elements. I’ve looked around, but it’s not clear to me how to accomplish this.

I have a little experimental project here:

(Matt) #2

Have you seen the Get____ methods?

My example config is in toml because it’s what I have handy. Viper is agnostic to the config format. A configuration struct is not required, Viper handles this for you.

key = "value"

Could be loaded with

if err := viper.ReadInConfig(); err == nil {
	fmt.Println("Using config file:", viper.ConfigFileUsed())

And values could be accessed with

value := viper.GetString("section.key")

If you need a more complete example I can try to write one up.

(Ryan Quinn) #3

value := viper.GetString("section.key") works in the subcommand after viper is imported.

It wasn’t clear that viper instances would inherit the config loaded in the root file. I was thinking I needed to access the viper config through cobra some how.

Thanks for the help!