From f1fe33b68e27915b9166f7865515b48169ae617c Mon Sep 17 00:00:00 2001 From: inhere Date: Tue, 19 Jan 2021 22:47:38 +0800 Subject: [PATCH] up: use func var instead of the global var --- CHANGELOG.md | 3 +++ data_source.go | 20 ++++++++++++-------- validators.go | 1 - 3 files changed, 15 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b17a7bb..4ac2716 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ ## V2 - TODO +- [ ] inner validators always use reflect.Value as param. + - `Enum(val, enum interface{})` -> `ReflectVEnum(val, enum interface{})` + - can register custom type - use sync.Pool for optimize create Validation. diff --git a/data_source.go b/data_source.go index d97cd16..9d2e32e 100644 --- a/data_source.go +++ b/data_source.go @@ -41,10 +41,8 @@ var timeType = reflect.TypeOf(time.Time{}) // data (Un)marshal func var ( - subField string - parentField string - Marshal MarshalFunc = json.Marshal - Unmarshal UnmarshalFunc = json.Unmarshal + Marshal MarshalFunc = json.Marshal + Unmarshal UnmarshalFunc = json.Unmarshal ) type ( @@ -396,14 +394,13 @@ func (d *StructData) loadMessagesFromTag(trans *Translator, field, vRule, vMsg s // Get value by field name func (d *StructData) Get(field string) (interface{}, bool) { - var fv reflect.Value field = strutil.UpperFirst(field) if strings.ContainsRune(field, '.') { // want get sub struct field ss := strings.SplitN(field, ".", 2) - parentField, subField = ss[0], ss[1] + parentField, subField := ss[0], ss[1] // check top field is an struct tft, ok := d.valueTpy.FieldByName(parentField) @@ -463,13 +460,20 @@ func (d *StructData) Get(field string) (interface{}, bool) { // Set value by field name. // Notice: `StructData.src` the incoming struct must be a pointer to set the value func (d *StructData) Set(field string, val interface{}) (newVal interface{}, err error) { - var fv reflect.Value field = strutil.UpperFirst(field) if !d.HasField(field) { // field not found return nil, ErrNoField } + + var topField, subField string + // want get sub struct field + if strings.ContainsRune(field, '.') { + ss := strings.SplitN(field, ".", 2) + topField, subField = ss[0], ss[1] + } + fv, ok := d.fieldValues[field] if !ok { f := d.fieldNames[field] @@ -479,7 +483,7 @@ func (d *StructData) Set(field string, val interface{}) (newVal interface{}, err case fieldAtAnonymous: fv = d.value.FieldByName(subField) case fieldAtSubStruct: - fv = d.value.FieldByName(parentField) + fv = d.value.FieldByName(topField) if fv.Type().Kind() == reflect.Ptr { fv = removeValuePtr(fv) } diff --git a/validators.go b/validators.go index b8ad114..90b6b45 100644 --- a/validators.go +++ b/validators.go @@ -1100,7 +1100,6 @@ func Between(val interface{}, min, max int64) bool { // convert custom type to int or string or unit func convert(val interface{}) (value interface{}, err error) { - v := reflect.ValueOf(val) switch v.Kind() {