1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
|
package jsoninfo
import (
"reflect"
"sort"
"sync"
)
var (
typeInfos = map[reflect.Type]*TypeInfo{}
typeInfosMutex sync.RWMutex
)
// TypeInfo contains information about JSON serialization of a type
type TypeInfo struct {
Type reflect.Type
Fields []FieldInfo
}
func GetTypeInfoForValue(value interface{}) *TypeInfo {
return GetTypeInfo(reflect.TypeOf(value))
}
// GetTypeInfo returns TypeInfo for the given type.
func GetTypeInfo(t reflect.Type) *TypeInfo {
for t.Kind() == reflect.Ptr {
t = t.Elem()
}
typeInfosMutex.RLock()
typeInfo, exists := typeInfos[t]
typeInfosMutex.RUnlock()
if exists {
return typeInfo
}
if t.Kind() != reflect.Struct {
typeInfo = &TypeInfo{
Type: t,
}
} else {
// Allocate
typeInfo = &TypeInfo{
Type: t,
Fields: make([]FieldInfo, 0, 16),
}
// Add fields
typeInfo.Fields = AppendFields(nil, nil, t)
// Sort fields
sort.Sort(sortableFieldInfos(typeInfo.Fields))
}
// Publish
typeInfosMutex.Lock()
typeInfos[t] = typeInfo
typeInfosMutex.Unlock()
return typeInfo
}
// FieldNames returns all field names
func (typeInfo *TypeInfo) FieldNames() []string {
fields := typeInfo.Fields
names := make([]string, len(fields))
for i, field := range fields {
names[i] = field.JSONName
}
return names
}
|