mapping.go 1.5 KB
package utils

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

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
}