2020-08-20 06:38:50 +03:00
|
|
|
package json
|
|
|
|
|
|
|
|
import (
|
|
|
|
"reflect"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
func getTag(field reflect.StructField) string {
|
|
|
|
return field.Tag.Get("json")
|
|
|
|
}
|
|
|
|
|
|
|
|
func isIgnoredStructField(field reflect.StructField) bool {
|
2020-08-22 12:15:39 +03:00
|
|
|
if field.PkgPath != "" {
|
|
|
|
if field.Anonymous {
|
|
|
|
if !(field.Type.Kind() == reflect.Ptr && field.Type.Elem().Kind() == reflect.Struct) && field.Type.Kind() != reflect.Struct {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
// private field
|
|
|
|
return true
|
|
|
|
}
|
2020-08-20 06:38:50 +03:00
|
|
|
}
|
|
|
|
tag := getTag(field)
|
|
|
|
if tag == "-" {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
type structTag struct {
|
|
|
|
key string
|
2020-08-22 09:40:18 +03:00
|
|
|
isTaggedKey bool
|
2020-08-20 06:38:50 +03:00
|
|
|
isOmitEmpty bool
|
|
|
|
isString bool
|
2020-08-22 06:58:34 +03:00
|
|
|
field reflect.StructField
|
|
|
|
}
|
|
|
|
|
|
|
|
type structTags []*structTag
|
|
|
|
|
|
|
|
func (t structTags) existsKey(key string) bool {
|
|
|
|
for _, tt := range t {
|
|
|
|
if tt.key == key {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
2020-08-20 06:38:50 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func structTagFromField(field reflect.StructField) *structTag {
|
|
|
|
keyName := field.Name
|
|
|
|
tag := getTag(field)
|
2020-08-22 09:40:18 +03:00
|
|
|
st := &structTag{field: field}
|
2020-08-20 06:38:50 +03:00
|
|
|
opts := strings.Split(tag, ",")
|
|
|
|
if len(opts) > 0 {
|
|
|
|
if opts[0] != "" {
|
|
|
|
keyName = opts[0]
|
2020-08-22 09:40:18 +03:00
|
|
|
st.isTaggedKey = true
|
2020-08-20 06:38:50 +03:00
|
|
|
}
|
|
|
|
}
|
2020-08-22 09:40:18 +03:00
|
|
|
st.key = keyName
|
2020-08-20 06:38:50 +03:00
|
|
|
if len(opts) > 1 {
|
|
|
|
st.isOmitEmpty = opts[1] == "omitempty"
|
|
|
|
st.isString = opts[1] == "string"
|
|
|
|
}
|
|
|
|
return st
|
|
|
|
}
|