Register maker is added. (#149)
# Describe Request Register maker is added. # Change Type New code.
This commit is contained in:
parent
23f3064805
commit
b9d2edb3cd
2 changed files with 55 additions and 0 deletions
|
|
@ -46,6 +46,11 @@ var makers = map[string]MakeCheckFunc{
|
|||
nameURLUnescape: makeURLUnescape,
|
||||
}
|
||||
|
||||
// RegisterMaker registers a new maker function with the given name.
|
||||
func RegisterMaker(name string, maker MakeCheckFunc) {
|
||||
makers[name] = maker
|
||||
}
|
||||
|
||||
// makeChecks take a checker config and returns the check functions.
|
||||
func makeChecks(config string) []CheckFunc[reflect.Value] {
|
||||
fields := strings.Fields(config)
|
||||
|
|
|
|||
|
|
@ -6,6 +6,8 @@
|
|||
package v2_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
v2 "github.com/cinar/checker/v2"
|
||||
|
|
@ -24,3 +26,51 @@ func TestMakeCheckersUnknown(t *testing.T) {
|
|||
|
||||
v2.CheckStruct(person)
|
||||
}
|
||||
|
||||
func ExampleRegisterMaker() {
|
||||
v2.RegisterMaker("is-fruit", func(params string) v2.CheckFunc[reflect.Value] {
|
||||
return func(value reflect.Value) (reflect.Value, error) {
|
||||
stringValue := value.Interface().(string)
|
||||
|
||||
if stringValue == "apple" || stringValue == "banana" {
|
||||
return value, nil
|
||||
}
|
||||
|
||||
return value, v2.NewCheckError("NOT_FRUIT")
|
||||
}
|
||||
})
|
||||
|
||||
type Item struct {
|
||||
Name string `checkers:"is-fruit"`
|
||||
}
|
||||
|
||||
person := &Item{
|
||||
Name: "banana",
|
||||
}
|
||||
|
||||
err, ok := v2.CheckStruct(person)
|
||||
if !ok {
|
||||
fmt.Println(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegisterMaker(t *testing.T) {
|
||||
v2.RegisterMaker("unknown", func(params string) v2.CheckFunc[reflect.Value] {
|
||||
return func(value reflect.Value) (reflect.Value, error) {
|
||||
return value, nil
|
||||
}
|
||||
})
|
||||
|
||||
type Person struct {
|
||||
Name string `checkers:"unknown"`
|
||||
}
|
||||
|
||||
person := &Person{
|
||||
Name: "Onur",
|
||||
}
|
||||
|
||||
_, ok := v2.CheckStruct(person)
|
||||
if !ok {
|
||||
t.Fatal("expected valid")
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue