Register maker is added. (#149)

# Describe Request

Register maker is added.

# Change Type

New code.
This commit is contained in:
Onur Cinar 2024-12-27 07:44:26 -08:00 committed by GitHub
commit b9d2edb3cd
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 55 additions and 0 deletions

View file

@ -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)

View file

@ -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")
}
}