Access Config in Subcommands

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: https://github.com/jollyrogue/gocobra-exp

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.

[section]
key = "value"

Could be loaded with

viper.SetConfigFile(cfgFile)
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.

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!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.