validate/input.go

42 lines
836 B
Go
Raw Permalink Normal View History

2018-10-16 20:18:39 +02:00
package validate
import (
"reflect"
"regexp"
"strconv"
)
func inputInt(kind reflect.Kind, value string) interface{} {
return int(inputSame(reflect.Int, value).(int64))
}
func inputRegexp(kind reflect.Kind, value string) interface{} {
return regexp.MustCompile(value)
}
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
}