File: type_info.go

package info (click to toggle)
golang-github-getkin-kin-openapi 0.1.0+git20181119.fa639d0-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 480 kB
  • sloc: makefile: 2
file content (68 lines) | stat: -rw-r--r-- 1,290 bytes parent folder | download
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
}