aicra/validator/bool.go

42 lines
886 B
Go
Raw Normal View History

package validator
import (
"reflect"
)
// BoolType makes the "bool" type available in the aicra configuration
// It considers valid:
// - booleans
// - strings containing "true" or "false"
// - []byte containing "true" or "false"
type BoolType struct{}
// GoType returns the `bool` type
func (BoolType) GoType() reflect.Type {
2020-03-28 18:11:23 +00:00
return reflect.TypeOf(true)
}
// Validator for bool values
func (BoolType) Validator(typename string, avail ...Type) ValidateFunc {
if typename != "bool" {
return nil
}
return func(value interface{}) (interface{}, bool) {
switch cast := value.(type) {
case bool:
return cast, true
case string:
strVal := string(cast)
return strVal == "true", strVal == "true" || strVal == "false"
case []byte:
strVal := string(cast)
return strVal == "true", strVal == "true" || strVal == "false"
default:
return false, false
}
}
}