mapping.go 1.7 KB
package utils

import (
	"github.com/tiptok/gocomm/common"
	"reflect"
	"time"
)

func LoadCustomFieldToMap(src interface{}, fields ...string) map[string]interface{} {
	rsp := LoadCustomField(src, fields...)
	if rsp == nil {
		return map[string]interface{}{}
	}
	return rsp.(map[string]interface{})
}

func LoadCustomField(src interface{}, fields ...string) interface{} {
	typeSrc := reflect.TypeOf(src)
	valueSrc := reflect.ValueOf(src)

	if v, ok := src.(reflect.Value); ok {
		valueSrc = v
		typeSrc = v.Type()
	}
	if typeSrc.Kind() == reflect.Ptr {
		valueSrc = valueSrc.Elem()
	}
	k := valueSrc.Kind()
	switch k {
	case reflect.Array, reflect.Slice:
		len := valueSrc.Len()
		retSliceMap := make([]map[string]interface{}, 0)
		if len == 0 {
			return retSliceMap
		}
		for i := 0; i < len; i++ {
			v := valueSrc.Index(i)
			retSliceMap = append(retSliceMap, (LoadCustomField(v, fields...)).(map[string]interface{}))
		}
		return retSliceMap
	case reflect.Struct:
		retSliceMap := make(map[string]interface{})
		for _, filed := range fields {
			f := valueSrc.FieldByName(filed)
			if !f.IsValid() {
				continue
			}
			v := f.Interface()
			if t, ok := v.(time.Time); ok {
				v = t.Local().Format("2006-01-02 15:04:05")
			}
			retSliceMap[common.CamelCase(filed, false)] = v
		}
		return retSliceMap
	default:
		return src
	}
	return src
}

func AppendCustomField(src interface{}, options map[string]interface{}) interface{} {
	var mapSrc map[string]interface{}
	var ok bool
	mapSrc, ok = src.(map[string]interface{})
	if !ok {
		common.JsonUnmarshal(common.JsonAssertString(src), &mapSrc)
	}
	for field, value := range options {
		mapSrc[common.CamelCase(field, false)] = value
	}
	return mapSrc
}