mirror of https://github.com/spf13/viper.git
Adding the ability to get into a struct
This commit is contained in:
parent
7f5b583ff1
commit
af373af72c
23
viper.go
23
viper.go
|
@ -20,6 +20,7 @@ import (
|
||||||
|
|
||||||
"github.com/BurntSushi/toml"
|
"github.com/BurntSushi/toml"
|
||||||
"github.com/kr/pretty"
|
"github.com/kr/pretty"
|
||||||
|
"github.com/mitchellh/mapstructure"
|
||||||
"github.com/spf13/cast"
|
"github.com/spf13/cast"
|
||||||
jww "github.com/spf13/jwalterweatherman"
|
jww "github.com/spf13/jwalterweatherman"
|
||||||
"gopkg.in/yaml.v1"
|
"gopkg.in/yaml.v1"
|
||||||
|
@ -93,6 +94,28 @@ func GetStringMapString(key string) map[string]string {
|
||||||
return cast.ToStringMapString(Get(key))
|
return cast.ToStringMapString(Get(key))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// takes a map and uses reflection to convert it into the given Go native structure.
|
||||||
|
// rawVal must be a pointer to a struct.
|
||||||
|
func GetIntoStruct(key string, rawVal interface{}) error {
|
||||||
|
return mapstructure.Decode(Get(key), rawVal)
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetAllIntoStruct(rawVal interface{}) (err error) {
|
||||||
|
err = mapstructure.Decode(defaults, rawVal)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
err = mapstructure.Decode(config, rawVal)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
err = mapstructure.Decode(override, rawVal)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
func find(key string) interface{} {
|
func find(key string) interface{} {
|
||||||
var val interface{}
|
var val interface{}
|
||||||
var exists bool
|
var exists bool
|
||||||
|
|
|
@ -128,3 +128,29 @@ func TestRecursiveAliases(t *testing.T) {
|
||||||
RegisterAlias("Baz", "Roo")
|
RegisterAlias("Baz", "Roo")
|
||||||
RegisterAlias("Roo", "baz")
|
RegisterAlias("Roo", "baz")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestIntoStruct(t *testing.T) {
|
||||||
|
SetDefault("port", 1313)
|
||||||
|
Set("name", "Steve")
|
||||||
|
|
||||||
|
type config struct {
|
||||||
|
Port int
|
||||||
|
Name string
|
||||||
|
}
|
||||||
|
|
||||||
|
var C config
|
||||||
|
|
||||||
|
err := GetAllIntoStruct(&C)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unable to decode into struct, %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
assert.Equal(t, &C, &config{Name: "Steve", Port: 1313})
|
||||||
|
|
||||||
|
Set("port", 1234)
|
||||||
|
err = GetAllIntoStruct(&C)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unable to decode into struct, %v", err)
|
||||||
|
}
|
||||||
|
assert.Equal(t, &C, &config{Name: "Steve", Port: 1234})
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in New Issue