Skip to content

Instantly share code, notes, and snippets.

@mortymacs
Created April 3, 2023 14:02
Show Gist options
  • Save mortymacs/3446a673df2c582b58b2b8a3f64f7f3d to your computer and use it in GitHub Desktop.
Save mortymacs/3446a673df2c582b58b2b8a3f64f7f3d to your computer and use it in GitHub Desktop.
mapstructure custom data type
package main
import (
"fmt"
"log"
"reflect"
"github.com/mitchellh/mapstructure"
)
type Data struct {
Countries []string
City string
Active bool
}
func StrToBool(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) {
if t.Kind() != reflect.Bool {
return data, nil
}
// Convert it by parsing
if data.(string) == "true" {
return true, nil
} else if data.(string) == "false" {
return false, nil
}
return nil, fmt.Errorf("failed parsing bool %v", data)
}
func main() {
map_data := map[string]string{
"countries": "IR,US",
"city": "test",
"active": "true",
}
var data Data
cfg := &mapstructure.DecoderConfig{
DecodeHook: mapstructure.ComposeDecodeHookFunc(StrToBool, mapstructure.StringToSliceHookFunc(",")),
Result: &data,
}
ms, _ := mapstructure.NewDecoder(cfg)
if err := ms.Decode(map_data); err != nil {
log.Fatalf("Failed! %s", err)
}
fmt.Printf("%#v\n", data)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment