package utility import ( "github.com/mitchellh/mapstructure" "reflect" "time" ) // 映射; type maps struct { } // 构建; func Maps() *maps { return &maps{} } // 转为结构体; func (this *maps) Struct(src, dst interface{}) error { config := &mapstructure.DecoderConfig{ WeaklyTypedInput: true, DecodeHook: mapstructure.ComposeDecodeHookFunc(ToTimeHookFunc()), Result: &dst, } decoder, err := mapstructure.NewDecoder(config) if err != nil { return err } if err = decoder.Decode(src); err != nil { return err } return nil } func ToTimeHookFunc() mapstructure.DecodeHookFunc { return func( f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) { if t != reflect.TypeOf(time.Time{}) { return data, nil } switch f.Kind() { case reflect.String: return time.Parse(time.RFC3339, data.(string)) case reflect.Float64: return time.Unix(0, int64(data.(float64))*int64(time.Millisecond)), nil case reflect.Int64: return time.Unix(0, data.(int64)*int64(time.Millisecond)), nil default: return data, nil } } }