Skip to content

Commit

Permalink
up: use func var instead of the global var
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Jan 19, 2021
1 parent 4078096 commit f1fe33b
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 9 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Expand Up @@ -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.

Expand Down
20 changes: 12 additions & 8 deletions data_source.go
Expand Up @@ -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 (
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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]
Expand All @@ -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)
}
Expand Down
1 change: 0 additions & 1 deletion validators.go
Expand Up @@ -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() {
Expand Down

0 comments on commit f1fe33b

Please sign in to comment.