typeFields returns a list of fields that JSON should recognize for the given type. The algorithm is breadth-first search over the set of structs to include - the top struct and then any reachable anonymous structs.
(t reflect.Type)
| 1069 | // The algorithm is breadth-first search over the set of structs to include - the top struct |
| 1070 | // and then any reachable anonymous structs. |
| 1071 | func typeFields(t reflect.Type) []field { |
| 1072 | // Anonymous fields to explore at the current level and the next. |
| 1073 | current := []field{} |
| 1074 | next := []field{{typ: t}} |
| 1075 | |
| 1076 | // Count of queued names for current level and the next. |
| 1077 | var count map[reflect.Type]int |
| 1078 | nextCount := map[reflect.Type]int{} |
| 1079 | |
| 1080 | // Types already visited at an earlier level. |
| 1081 | visited := map[reflect.Type]bool{} |
| 1082 | |
| 1083 | // Fields found. |
| 1084 | var fields []field |
| 1085 | |
| 1086 | // Buffer to run HTMLEscape on field names. |
| 1087 | var nameEscBuf bytes.Buffer |
| 1088 | |
| 1089 | for len(next) > 0 { |
| 1090 | current, next = next, current[:0] |
| 1091 | count, nextCount = nextCount, map[reflect.Type]int{} |
| 1092 | |
| 1093 | for _, f := range current { |
| 1094 | if visited[f.typ] { |
| 1095 | continue |
| 1096 | } |
| 1097 | visited[f.typ] = true |
| 1098 | |
| 1099 | // Scan f.typ for fields to include. |
| 1100 | for i := 0; i < f.typ.NumField(); i++ { |
| 1101 | sf := f.typ.Field(i) |
| 1102 | isUnexported := sf.PkgPath != "" |
| 1103 | if sf.Anonymous { |
| 1104 | t := sf.Type |
| 1105 | if t.Kind() == reflect.Ptr { |
| 1106 | t = t.Elem() |
| 1107 | } |
| 1108 | if isUnexported && t.Kind() != reflect.Struct { |
| 1109 | // Ignore embedded fields of unexported non-struct types. |
| 1110 | continue |
| 1111 | } |
| 1112 | // Do not ignore embedded fields of unexported struct types |
| 1113 | // since they may have exported fields. |
| 1114 | } else if isUnexported { |
| 1115 | // Ignore unexported non-embedded fields. |
| 1116 | continue |
| 1117 | } |
| 1118 | tag := sf.Tag.Get("json") |
| 1119 | if tag == "-" { |
| 1120 | continue |
| 1121 | } |
| 1122 | name, opts := parseTag(tag) |
| 1123 | if !isValidTag(name) { |
| 1124 | name = "" |
| 1125 | } |
| 1126 | index := make([]int, len(f.index)+1) |
| 1127 | copy(index, f.index) |
| 1128 | index[len(f.index)] = i |
no test coverage detected