33 lines
638 B
Go
33 lines
638 B
Go
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:]
|
|
}
|