Fixes "Can't unmarshal JSON array with #63"

This commit is contained in:
Manu Mtz-Almeida 2014-07-13 00:17:01 +02:00
parent 2078ecd8e1
commit e2242b59e6
1 changed files with 36 additions and 21 deletions

View File

@ -152,7 +152,6 @@ func ensureNotPointer(obj interface{}) {
} }
func Validate(obj interface{}) error { func Validate(obj interface{}) error {
typ := reflect.TypeOf(obj) typ := reflect.TypeOf(obj)
val := reflect.ValueOf(obj) val := reflect.ValueOf(obj)
@ -161,30 +160,46 @@ func Validate(obj interface{}) error {
val = val.Elem() val = val.Elem()
} }
switch typ.Kind() {
case reflect.Struct:
for i := 0; i < typ.NumField(); i++ { for i := 0; i < typ.NumField(); i++ {
field := typ.Field(i) field := typ.Field(i)
// Allow ignored fields in the struct
if field.Tag.Get("form") == "-" {
continue
}
fieldValue := val.Field(i).Interface() fieldValue := val.Field(i).Interface()
zero := reflect.Zero(field.Type).Interface() zero := reflect.Zero(field.Type).Interface()
// Validate nested and embedded structs (if pointer, only do so if not nil) if strings.Index(field.Tag.Get("binding"), "required") > -1 {
if field.Type.Kind() == reflect.Struct || fieldType := field.Type.Kind()
(field.Type.Kind() == reflect.Ptr && !reflect.DeepEqual(zero, fieldValue)) { if fieldType == reflect.Struct {
if err := Validate(fieldValue); err != nil { err := Validate(fieldValue)
if err != nil {
return err
}
} else if reflect.DeepEqual(zero, fieldValue) {
return errors.New("Required " + field.Name)
} else if fieldType == reflect.Slice && field.Type.Elem().Kind() == reflect.Struct {
err := Validate(fieldValue)
if err != nil {
return err return err
} }
} }
if strings.Index(field.Tag.Get("binding"), "required") > -1 {
if reflect.DeepEqual(zero, fieldValue) {
name := field.Name
if j := field.Tag.Get("json"); j != "" {
name = j
} else if f := field.Tag.Get("form"); f != "" {
name = f
}
return errors.New("Required " + name)
} }
} }
case reflect.Slice:
for i := 0; i < val.Len(); i++ {
fieldValue := val.Index(i).Interface()
err := Validate(fieldValue)
if err != nil {
return err
}
}
default:
return nil
} }
return nil return nil
} }