go-json/struct_field.go

82 lines
1.6 KiB
Go
Raw Permalink Normal View History

2020-08-20 06:38:50 +03:00
package json
import (
"reflect"
"strings"
2020-09-16 19:26:39 +03:00
"unicode"
2020-08-20 06:38:50 +03:00
)
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)
2021-02-01 16:31:39 +03:00
return tag == "-"
2020-08-20 06:38:50 +03:00
}
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
}
2020-09-16 19:26:39 +03:00
func isValidTag(s string) bool {
if s == "" {
return false
}
for _, c := range s {
switch {
case strings.ContainsRune("!#$%&()*+-./:<=>?@[]^_{|}~ ", c):
// Backslash and quote chars are reserved, but
// otherwise any punctuation chars are allowed
// in a tag name.
case !unicode.IsLetter(c) && !unicode.IsDigit(c):
return false
}
}
return true
}
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 {
2020-09-16 19:26:39 +03:00
if opts[0] != "" && isValidTag(opts[0]) {
2020-08-20 06:38:50 +03:00
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
}