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()
} }
for i := 0; i < typ.NumField(); i++ { switch typ.Kind() {
field := typ.Field(i) case reflect.Struct:
fieldValue := val.Field(i).Interface() for i := 0; i < typ.NumField(); i++ {
zero := reflect.Zero(field.Type).Interface() field := typ.Field(i)
// Validate nested and embedded structs (if pointer, only do so if not nil) // Allow ignored fields in the struct
if field.Type.Kind() == reflect.Struct || if field.Tag.Get("form") == "-" {
(field.Type.Kind() == reflect.Ptr && !reflect.DeepEqual(zero, fieldValue)) { continue
if err := Validate(fieldValue); err != nil { }
fieldValue := val.Field(i).Interface()
zero := reflect.Zero(field.Type).Interface()
if strings.Index(field.Tag.Get("binding"), "required") > -1 {
fieldType := field.Type.Kind()
if fieldType == reflect.Struct {
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
}
}
}
}
case reflect.Slice:
for i := 0; i < val.Len(); i++ {
fieldValue := val.Index(i).Interface()
err := Validate(fieldValue)
if err != nil {
return err return err
} }
} }
default:
if strings.Index(field.Tag.Get("binding"), "required") > -1 { return nil
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)
}
}
} }
return nil return nil
} }