tkcashgame_v4/pkg/utils/struct.go

33 lines
638 B
Go
Raw Permalink Normal View History

2025-10-22 10:01:11 +00:00
package utils
import (
"reflect"
"strings"
)
// StructToMapJson struct to map json tag
func StructToMapJson(obj interface{}) map[string]interface{} {
t := reflect.TypeOf(obj)
v := reflect.ValueOf(obj)
var data = make(map[string]interface{})
for i := 0; i < t.NumField(); i++ {
jsonKey := t.Field(i).Tag.Get("json")
if jsonKey != "-" {
// tagName, tagOpts
tagName, _ := parseTags(jsonKey)
data[tagName] = v.Field(i).Interface()
}
}
return data
}
// parseTags "age,omitempty"
func parseTags(s string) (string, []string) {
if len(s) == 0 {
return "", nil
}
sl := strings.Split(s, ",")
return sl[0], sl[1:]
}