mirror of
https://github.com/yudai/gotty.git
synced 2026-01-03 08:08:50 +01:00
generate falgs based on struct options instead of defining them externally
This commit is contained in:
parent
c4ed7bc415
commit
d71e2fcfa8
6 changed files with 218 additions and 231 deletions
41
utils/default.go
Normal file
41
utils/default.go
Normal 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
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue