Skip to content

Commit

Permalink
feat: use cache in getFiledNamesByJSONKeys()
Browse files Browse the repository at this point in the history
  • Loading branch information
DavidCai1111 committed Jan 31, 2018
1 parent 452bacb commit 0b979c4
Showing 1 changed file with 22 additions and 5 deletions.
27 changes: 22 additions & 5 deletions util.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,36 @@ package jsonmask

import (
"reflect"
"sync"

"gopkg.in/oleiade/reflections.v1"
)

var (
structTagCache = sync.Map{}
)

func getFiledNamesByJSONKeys(obj interface{}, jsonKeys []string) (map[string]string, error) {
fieldNames := make(map[string]string)
var (
fieldNames = make(map[string]string)
structName = reflect.TypeOf(obj).Name()
fieldTagMap = map[string]string{}
err error
)

cache, ok := structTagCache.Load(structName)
if !ok {
fieldTagMap, err = reflections.TagsDeep(obj, "json")
if err != nil {
return nil, err
}

m, err := reflections.TagsDeep(obj, "json")
if err != nil {
return nil, err
structTagCache.Store(structName, fieldTagMap)
} else {
fieldTagMap = cache.(map[string]string)
}

for fieldName, key := range m {
for fieldName, key := range fieldTagMap {
for _, jsonKey := range jsonKeys {
if key == jsonKey {
fieldNames[jsonKey] = fieldName
Expand Down

0 comments on commit 0b979c4

Please sign in to comment.