2017-05-06 17:55:02 +02:00
package modelHelper
import (
"reflect"
2017-05-06 18:15:02 +02:00
"net/http"
2017-05-06 18:02:54 +02:00
"github.com/ewhal/nyaa/util/log"
2017-05-06 18:52:27 +02:00
"strconv"
2017-05-06 17:55:02 +02:00
)
func IsZeroOfUnderlyingType ( x interface { } ) bool {
return x == reflect . Zero ( reflect . TypeOf ( x ) ) . Interface ( )
}
// AssignValue assign form values to model.
func AssignValue ( model interface { } , form interface { } ) {
modelIndirect := reflect . Indirect ( reflect . ValueOf ( model ) )
formElem := reflect . ValueOf ( form ) . Elem ( )
typeOfTForm := formElem . Type ( )
for i := 0 ; i < formElem . NumField ( ) ; i ++ {
2017-05-07 14:53:01 +02:00
tag := typeOfTForm . Field ( i ) . Tag
if tag . Get ( "omit" ) != "false" {
modelField := modelIndirect . FieldByName ( typeOfTForm . Field ( i ) . Name )
if modelField . IsValid ( ) {
formField := formElem . Field ( i )
modelField . Set ( formField )
} else {
log . Warnf ( "modelField : %s - %s" , typeOfTForm . Field ( i ) . Name , modelField )
}
2017-05-06 17:55:02 +02:00
}
}
}
2017-05-06 18:02:54 +02:00
// AssignValue assign form values to model.
func BindValueForm ( form interface { } , r * http . Request ) {
r . ParseForm ( )
formElem := reflect . ValueOf ( form ) . Elem ( )
for i := 0 ; i < formElem . NumField ( ) ; i ++ {
2017-05-06 18:52:27 +02:00
typeField := formElem . Type ( ) . Field ( i )
tag := typeField . Tag
2017-05-06 18:55:33 +02:00
switch typeField . Type . Name ( ) {
2017-05-06 18:52:27 +02:00
case "string" :
formElem . Field ( i ) . SetString ( r . PostFormValue ( tag . Get ( "form" ) ) )
case "int" :
nbr , _ := strconv . Atoi ( r . PostFormValue ( tag . Get ( "form" ) ) )
2017-05-06 18:58:48 +02:00
formElem . Field ( i ) . SetInt ( int64 ( nbr ) )
2017-05-06 18:52:27 +02:00
case "float" :
nbr , _ := strconv . Atoi ( r . PostFormValue ( tag . Get ( "form" ) ) )
formElem . Field ( i ) . SetFloat ( float64 ( nbr ) )
2017-05-06 18:55:33 +02:00
}
2017-05-06 18:02:54 +02:00
}
2017-05-06 18:55:33 +02:00
}