func(d *StructTagDecoder) Decode(i interface{}) map[string]interface{} { v := reflect.ValueOf(i) if v.Kind() == reflect.Ptr { v = v.Elem() } if v.Kind() != reflect.Struct { panic(fmt.Errorf("toMap only accepts structs, got (%T)", v)) } typ := v.Type() out := make(map[string]interface{}) for i := 0; i < v.NumField(); i++ { fi := typ.Field(i) if tagv := fi.Tag.Get(d.tag); tagv != "" { field := v.Field(i).Interface() if field != reflect.Zero(reflect.TypeOf(field)).Interface() { out[tagv] = v.Field(i).Interface() } } } return out }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
type Student struct { Name string`json:"name"` Age int`json:"age"` }
func(d *StructTagDecoder) Decode(i interface{}) map[string]interface{} { v := reflect.ValueOf(i) if v.Kind() == reflect.Ptr { v = v.Elem() } if v.Kind() != reflect.Struct { panic(fmt.Errorf("toMap only accepts structs, got (%T)", v)) } typ := v.Type() out := make(map[string]interface{}) for i := 0; i < v.NumField(); i++ { fi := typ.Field(i) if tagv := fi.Tag.Get(d.tag); tagv != "" { field := v.Field(i).Interface() if field != reflect.Zero(reflect.TypeOf(field)).Interface() { out[tagv] = v.Field(i).Interface() } } } return out }