You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
1.4 KiB

package mapstructure
import (
"github.com/mitchellh/mapstructure"
"github.com/shopspring/decimal"
"reflect"
)
// Decode @Title 解码
func Decode(input interface{}, output interface{}) error {
config := &mapstructure.DecoderConfig{
Metadata: nil,
Result: output,
TagName: "json",
DecodeHook: mapstructure.ComposeDecodeHookFunc(otherType),
}
decoder, err := mapstructure.NewDecoder(config)
if err != nil {
return err
}
return decoder.Decode(input)
}
// WeakDecode @Title 解码
func WeakDecode(input interface{}, output interface{}) error {
config := &mapstructure.DecoderConfig{
Metadata: nil,
Result: output,
TagName: "json",
WeaklyTypedInput: true,
DecodeHook: mapstructure.ComposeDecodeHookFunc(otherType),
}
decoder, err := mapstructure.NewDecoder(config)
if err != nil {
return err
}
return decoder.Decode(input)
}
// @Title 其他类型映射
func otherType(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) {
switch t {
case reflect.TypeOf(decimal.Decimal{}):
switch f.Kind() {
case reflect.String:
return decimal.NewFromString(data.(string))
case reflect.Int64:
return decimal.NewFromInt(data.(int64)), nil
case reflect.Float64:
return decimal.NewFromFloat(data.(float64)), nil
case reflect.Int32:
return decimal.NewFromInt32(data.(int32)), nil
}
}
return data, nil
}