1
0
mirror of https://github.com/astaxie/beego.git synced 2024-11-22 14:50:55 +00:00

beego.ParseForm() improvement

This commit is contained in:
Zaaksam 2016-09-01 15:04:57 +08:00
parent 3f67c62dd8
commit 7c2e563879

View File

@ -280,15 +280,8 @@ func AssetsCSS(src string) template.HTML {
} }
// ParseForm will parse form values to struct via tag. // ParseForm will parse form values to struct via tag.
func ParseForm(form url.Values, obj interface{}) error { // Support for anonymous struct.
objT := reflect.TypeOf(obj) func parseFormToStruct(form url.Values, objT reflect.Type, objV reflect.Value) error {
objV := reflect.ValueOf(obj)
if !isStructPtr(objT) {
return fmt.Errorf("%v must be a struct pointer", obj)
}
objT = objT.Elem()
objV = objV.Elem()
for i := 0; i < objT.NumField(); i++ { for i := 0; i < objT.NumField(); i++ {
fieldV := objV.Field(i) fieldV := objV.Field(i)
if !fieldV.CanSet() { if !fieldV.CanSet() {
@ -296,6 +289,14 @@ func ParseForm(form url.Values, obj interface{}) error {
} }
fieldT := objT.Field(i) fieldT := objT.Field(i)
if fieldT.Anonymous && fieldT.Type.Kind() == reflect.Struct {
err := parseFormToStruct(form, fieldT.Type, fieldV)
if err != nil {
return err
}
continue
}
tags := strings.Split(fieldT.Tag.Get("form"), ",") tags := strings.Split(fieldT.Tag.Get("form"), ",")
var tag string var tag string
if len(tags) == 0 || len(tags[0]) == 0 { if len(tags) == 0 || len(tags[0]) == 0 {
@ -384,6 +385,19 @@ func ParseForm(form url.Values, obj interface{}) error {
return nil return nil
} }
// ParseForm will parse form values to struct via tag.
func ParseForm(form url.Values, obj interface{}) error {
objT := reflect.TypeOf(obj)
objV := reflect.ValueOf(obj)
if !isStructPtr(objT) {
return fmt.Errorf("%v must be a struct pointer", obj)
}
objT = objT.Elem()
objV = objV.Elem()
return parseFormToStruct(form, objT, objV)
}
var sliceOfInts = reflect.TypeOf([]int(nil)) var sliceOfInts = reflect.TypeOf([]int(nil))
var sliceOfStrings = reflect.TypeOf([]string(nil)) var sliceOfStrings = reflect.TypeOf([]string(nil))