Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advanced configuration with the golang Viper lib

Tags:

yaml

config

go

I'm working on my first real Go project and have been searching for some tools to handle the configuration.

Finally, I've found this tool: https://github.com/spf13/viper which is really nice but I have some issues when I try to handle some more complex configurations such as the following config.yaml example:

app:
  name: "project-name"
  version 1

models:
  modelA:
    varA: "foo"
    varB: "bar"

  modelB:
    varA: "baz"
    varB: "qux"
    varC: "norf"

I don't know how to get the values from modelB for example. While looking at the lib code, I've found the followings but I don't really understand how to use it:

// Marshals the config into a Struct
func Marshal(rawVal interface{}) error {...}

func AllSettings() map[string]interface{} {...}

What I want is to be able, from everywhere in my package, to do something like:

modelsConf := viper.Get("models")
fmt.Println(modelsConf["modelA"]["varA"])

Could someone explain me the best way to achieve this?

like image 309
Cedric Morent Avatar asked Nov 25 '14 11:11

Cedric Morent


People also ask

What is viper in golang?

Viper is a complete configuration solution for Go applications including 12-Factor apps. It is designed to work within an application, and can handle all types of configuration needs and formats. It supports: setting defaults. reading from JSON, TOML, YAML, HCL, envfile and Java properties config files.

How does viper work Golang?

Viper will read a config string (as JSON, TOML, YAML, HCL or envfile) retrieved from a path in a Key/Value store such as etcd or Consul. These values take precedence over default values, but are overridden by configuration values retrieved from disk, flags, or environment variables.


1 Answers

Since the "models" block is a map, it's a bit easier to call

m := viper.GetStringMap("models")

m will be a map[string]interface {}

Then, you get the value of m[key], which is an interface {}, so you cast it to map[interface {}]interface {} :

m := v.GetStringMap("models")
mm := m["modelA"].(map[interface{}]interface{})

Now you can access "varA" key passing the key as an interface {} :

mmm := mm[string("varA")]

mmm is foo

like image 180
StevenLeRoux Avatar answered Sep 25 '22 00:09

StevenLeRoux