Skip to content

Instantly share code, notes, and snippets.

@suzuki-shunsuke
Last active March 29, 2018 05:16
Show Gist options
  • Save suzuki-shunsuke/795d448a8239c4a36adb7eb0a96aa99a to your computer and use it in GitHub Desktop.
Save suzuki-shunsuke/795d448a8239c4a36adb7eb0a96aa99a to your computer and use it in GitHub Desktop.
sample code of mapstructure's DecodeHook
package main
import (
"fmt"
"log"
"reflect"
"github.com/mitchellh/mapstructure"
"github.com/suzuki-shunsuke/go-set"
)
func main() {
a := []string{}
s := set.NewStrSet()
input := []interface{}{"foo"}
if err := mapstructure.Decode(input, &a); err != nil {
log.Fatal("failed to decode to []string: ", err)
}
fmt.Println("a:", a)
decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
DecodeHook: DecodeListToStrSet,
Result: s,
})
if err != nil {
log.Fatal("failed to get a new decoder: ", err)
}
if err := decoder.Decode(input); err != nil {
log.Fatal(err)
}
fmt.Println("s.ToList(): ", s.ToList())
}
func DecodeListToStrSet(fromType reflect.Type, toType reflect.Type, from interface{}) (interface{}, error) {
if reflect.TypeOf(set.StrSet{}) != toType {
return from, nil
}
if arr, ok := from.([]interface{}); ok {
s := set.NewStrSet()
for _, a := range arr {
if k, ok := a.(string); ok {
s.Add(k)
continue
}
return from, fmt.Errorf("type assertion to string is failure")
}
return s, nil
}
return from, nil
}
package main
import (
"fmt"
"log"
"github.com/mitchellh/mapstructure"
"github.com/suzuki-shunsuke/go-set"
)
func main() {
a := []string{}
s := set.NewStrSet()
input := []interface{}{"foo"}
if err := mapstructure.Decode(input, &a); err != nil {
log.Fatal("failed to decode to []string: ", err)
}
fmt.Println("a:", a)
if err := mapstructure.Decode(input, s); err != nil {
// '' expected a map, got 'slice'
// https://github.com/mitchellh/mapstructure/blob/60249754210871616548ae28fdadeecbd04303b3/mapstructure.go#L871
log.Fatal("failed to decode to set.StrSet: ", err)
}
fmt.Println("s:", s)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment