generate falgs based on struct options instead of defining them externally

This commit is contained in:
zlji 2017-01-09 22:06:46 +08:00 committed by Iwasaki Yudai
parent c4ed7bc415
commit d71e2fcfa8
6 changed files with 218 additions and 231 deletions

41
utils/default.go Normal file
View file

@ -0,0 +1,41 @@
package utils
import (
"fmt"
"github.com/fatih/structs"
"reflect"
"strconv"
)
func ApplyDefaultValues(struct_ interface{}) (err error) {
o := structs.New(struct_)
for _, field := range o.Fields() {
defaultValue := field.Tag("default")
if defaultValue == "" {
continue
}
var val interface{}
switch field.Kind() {
case reflect.String:
val = defaultValue
case reflect.Bool:
if defaultValue == "true" {
val = true
} else if defaultValue == "false" {
val = false
} else {
return fmt.Errorf("invalid bool expression: %v, use true/false", defaultValue)
}
case reflect.Int:
val, err = strconv.Atoi(defaultValue)
if err != nil {
return err
}
default:
val = field.Value()
}
field.Set(val)
}
return nil
}