From 8e90aaafac34db186dc5628fc83c62595c545a58 Mon Sep 17 00:00:00 2001 From: cmohrb Date: Tue, 21 Aug 2018 18:23:30 +0200 Subject: [PATCH] add method subSlice to get an array/table/list of config options as slice of "sub-vipers" --- viper.go | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/viper.go b/viper.go index db2d6d6..ca02fa6 100644 --- a/viper.go +++ b/viper.go @@ -1782,3 +1782,26 @@ func (v *Viper) Debug() { fmt.Printf("Config:\n%#v\n", v.config) fmt.Printf("Defaults:\n%#v\n", v.defaults) } + +func SubSlice(key string) (out []*Viper) { return v.SubSlice(key) } +func (v *Viper) SubSlice(key string) (out []*Viper) { + data := v.Get(key) + + if data == nil { + return nil + } + + if reflect.TypeOf(data).Kind() != reflect.Slice { + return nil + } + + for _, elem := range data.([]interface{}) { + subv := New() + if reflect.TypeOf(elem).Kind() == reflect.Map { + subv.config = cast.ToStringMap(elem) + out = append(out, subv) + } + } + + return +}