2021-01-28 08:28:24 +03:00
|
|
|
package hscan
|
|
|
|
|
|
|
|
import (
|
|
|
|
"reflect"
|
|
|
|
"strings"
|
|
|
|
"sync"
|
|
|
|
)
|
|
|
|
|
|
|
|
// structField represents a single field in a target struct.
|
|
|
|
type structField struct {
|
|
|
|
index int
|
|
|
|
fn decoderFunc
|
|
|
|
}
|
|
|
|
|
|
|
|
// structFields contains the list of all fields in a target struct.
|
|
|
|
type structFields struct {
|
|
|
|
m map[string]*structField
|
|
|
|
}
|
|
|
|
|
|
|
|
// structMap contains the map of struct fields for target structs
|
|
|
|
// indexed by the struct type.
|
|
|
|
type structMap struct {
|
|
|
|
m sync.Map
|
|
|
|
}
|
|
|
|
|
|
|
|
func newStructMap() *structMap {
|
2021-01-29 13:04:39 +03:00
|
|
|
return new(structMap)
|
2021-01-28 08:28:24 +03:00
|
|
|
}
|
|
|
|
|
2021-01-29 13:04:39 +03:00
|
|
|
func (s *structMap) get(t reflect.Type) *structFields {
|
|
|
|
if v, ok := s.m.Load(t); ok {
|
2021-01-29 13:12:47 +03:00
|
|
|
return v.(*structFields)
|
2021-01-28 08:28:24 +03:00
|
|
|
}
|
|
|
|
|
2021-01-29 13:12:47 +03:00
|
|
|
fMap := getStructFields(t, "redis")
|
2021-01-29 13:04:39 +03:00
|
|
|
s.m.Store(t, fMap)
|
2021-01-29 13:12:47 +03:00
|
|
|
return fMap
|
2021-01-28 08:28:24 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func newStructFields() *structFields {
|
|
|
|
return &structFields{
|
|
|
|
m: make(map[string]*structField),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *structFields) set(tag string, sf *structField) {
|
|
|
|
s.m[tag] = sf
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *structFields) get(tag string) (*structField, bool) {
|
|
|
|
f, ok := s.m[tag]
|
|
|
|
return f, ok
|
|
|
|
}
|
|
|
|
|
2021-01-29 13:12:47 +03:00
|
|
|
func getStructFields(t reflect.Type, fieldTag string) *structFields {
|
2021-01-28 08:28:24 +03:00
|
|
|
var (
|
2021-01-29 13:12:47 +03:00
|
|
|
num = t.NumField()
|
2021-01-28 08:28:24 +03:00
|
|
|
out = newStructFields()
|
|
|
|
)
|
|
|
|
|
|
|
|
for i := 0; i < num; i++ {
|
2021-01-29 13:12:47 +03:00
|
|
|
f := t.Field(i)
|
2021-01-28 08:28:24 +03:00
|
|
|
|
2021-01-29 13:12:47 +03:00
|
|
|
tag := t.Field(i).Tag.Get(fieldTag)
|
2021-01-28 08:28:24 +03:00
|
|
|
if tag == "" || tag == "-" {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
tag = strings.Split(tag, ",")[0]
|
|
|
|
if tag == "" {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// Use the built-in decoder.
|
2021-01-29 13:12:47 +03:00
|
|
|
out.set(tag, &structField{index: i, fn: decoders[f.Type.Kind()]})
|
2021-01-28 08:28:24 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
return out
|
|
|
|
}
|