validate/input.go

48 lines
1.1 KiB
Go

package validate
import (
"reflect"
"regexp"
"strconv"
)
// InputFunc is a function that converts the parameter of a validation rule to the desired type
type InputFunc func(reflect.Kind, string) interface{}
// InputInt always returns an int
func InputInt(kind reflect.Kind, value string) interface{} {
return int(InputSame(reflect.Int, value).(int64))
}
// InputRegexp always returns a compiled regular expression
func InputRegexp(kind reflect.Kind, value string) interface{} {
return regexp.MustCompile(value)
}
// InputSame returns the type matching the field
func InputSame(kind reflect.Kind, value string) interface{} {
var val interface{}
var err error
switch kind {
case reflect.String:
val = value
case reflect.Int:
val, err = strconv.ParseInt(value, 10, 64)
case reflect.Uint:
val, err = strconv.ParseUint(value, 10, 64)
case reflect.Float64:
val, err = strconv.ParseFloat(value, 64)
case reflect.Bool:
val, err = strconv.ParseBool(value)
default:
panic(`Cannot pass value to checks on type ` + kind.String())
}
if err != nil {
panic(`Invalid value "` + value + `"`)
}
return val
}