| 1 |
package runtime |
| 2 |
|
| 3 |
import ( |
| 4 |
"reflect" |
| 5 |
"strings" |
| 6 |
"unicode" |
| 7 |
) |
| 8 |
|
| 9 |
func getTag(field reflect.StructField) string { |
| 10 |
return field.Tag.Get("json") |
| 11 |
} |
| 12 |
|
| 13 |
func IsIgnoredStructField(field reflect.StructField) bool { |
| 14 |
if field.PkgPath != "" { |
| 15 |
if field.Anonymous { |
| 16 |
t := field.Type |
| 17 |
if t.Kind() == reflect.Ptr { |
| 18 |
t = t.Elem() |
| 19 |
} |
| 20 |
if t.Kind() != reflect.Struct { |
| 21 |
return true |
| 22 |
} |
| 23 |
} else { |
| 24 |
// private field |
| 25 |
return true |
| 26 |
} |
| 27 |
} |
| 28 |
tag := getTag(field) |
| 29 |
return tag == "-" |
| 30 |
} |
| 31 |
|
| 32 |
type StructTag struct { |
| 33 |
Key string |
| 34 |
IsTaggedKey bool |
| 35 |
IsOmitEmpty bool |
| 36 |
// IsOmitZero is whether the field has the omitzero option, which encoding/json has from Go 1.24: it is |
| 37 |
// false with an older Go, whose encoding/json ignores the option. |
| 38 |
IsOmitZero bool |
| 39 |
IsString bool |
| 40 |
Field reflect.StructField |
| 41 |
} |
| 42 |
|
| 43 |
type StructTags []*StructTag |
| 44 |
|
| 45 |
func (t StructTags) ExistsKey(key string) bool { |
| 46 |
for _, tt := range t { |
| 47 |
if tt.Key == key { |
| 48 |
return true |
| 49 |
} |
| 50 |
} |
| 51 |
return false |
| 52 |
} |
| 53 |
|
| 54 |
func isValidTag(s string) bool { |
| 55 |
if s == "" { |
| 56 |
return false |
| 57 |
} |
| 58 |
for _, c := range s { |
| 59 |
switch { |
| 60 |
case strings.ContainsRune("!#$%&()*+-./:<=>?@[]^_{|}~ ", c): |
| 61 |
// Backslash and quote chars are reserved, but |
| 62 |
// otherwise any punctuation chars are allowed |
| 63 |
// in a tag name. |
| 64 |
case !unicode.IsLetter(c) && !unicode.IsDigit(c): |
| 65 |
return false |
| 66 |
} |
| 67 |
} |
| 68 |
return true |
| 69 |
} |
| 70 |
|
| 71 |
func StructTagFromField(field reflect.StructField) *StructTag { |
| 72 |
keyName := field.Name |
| 73 |
tag := getTag(field) |
| 74 |
st := &StructTag{Field: field} |
| 75 |
opts := strings.Split(tag, ",") |
| 76 |
if len(opts) > 0 { |
| 77 |
if opts[0] != "" && isValidTag(opts[0]) { |
| 78 |
keyName = opts[0] |
| 79 |
st.IsTaggedKey = true |
| 80 |
} |
| 81 |
} |
| 82 |
st.Key = keyName |
| 83 |
if len(opts) > 1 { |
| 84 |
for _, opt := range opts[1:] { |
| 85 |
switch opt { |
| 86 |
case "omitempty": |
| 87 |
st.IsOmitEmpty = true |
| 88 |
case "omitzero": |
| 89 |
st.IsOmitZero = omitZeroOption |
| 90 |
case "string": |
| 91 |
st.IsString = true |
| 92 |
} |
| 93 |
} |
| 94 |
} |
| 95 |
return st |
| 96 |
} |