Skip to content

Instantly share code, notes, and snippets.

@nirasan
Last active February 9, 2017 00:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nirasan/4482b05ef6e2e273b606dc7a81acacdf to your computer and use it in GitHub Desktop.
Save nirasan/4482b05ef6e2e273b606dc7a81acacdf to your computer and use it in GitHub Desktop.
package argumenter
import (
"fmt"
"reflect"
"strconv"
"strings"
)
/*
* reflect version
*/
func ValidReflect(in interface{}) error {
v := reflect.ValueOf(in)
if v.Kind() != reflect.Ptr || v.Elem().Kind() != reflect.Struct {
return fmt.Errorf("must be pointer of struct")
}
vv := v.Elem()
t := vv.Type()
for i := 0; i < t.NumField(); i++ {
fv := vv.Field(i)
ft := t.Field(i)
for _, p := range strings.Split(ft.Tag.Get("arg"), ",") {
pair := strings.SplitN(p, "=", 2)
var intval int64
switch ft.Type.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
i, e := strconv.ParseInt(pair[1], 10, 64)
if e != nil {
return fmt.Errorf("%s field tag is invalid: %s", ft.Name, e)
}
intval = i
}
switch pair[0] {
case "max":
switch ft.Type.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if fv.Int() > intval {
return fmt.Errorf("%s field must less than %d: %d", ft.Name, intval, fv.Int())
}
}
case "min":
switch ft.Type.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if fv.Int() < intval {
return fmt.Errorf("%s field must greater than %d: %d", ft.Name, intval, fv.Int())
}
}
case "default":
switch ft.Type.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if fv.Int() == 0 {
fv.SetInt(intval)
}
}
}
}
}
return nil
}
/*
* generate version
*/
type MyArg struct {
Arg1 int `arg:"min=0,max=10,default=5"`
}
func ValidGenerate(in *MyArg) error {
if in.Arg1 > 10 {
return fmt.Errorf("Arg1 field must less than %d: %d", 10, in.Arg1)
}
if in.Arg1 < 0 {
return fmt.Errorf("Arg1 field must greater than %d: %d", 0, in.Arg1)
}
if in.Arg1 == 0 {
in.Arg1 = 5
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment