github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/kit/httptransport/transformer/util_validator.go (about) 1 package transformer 2 3 import ( 4 "context" 5 6 "github.com/machinefi/w3bstream/pkg/depends/kit/validator" 7 "github.com/machinefi/w3bstream/pkg/depends/x/reflectx" 8 "github.com/machinefi/w3bstream/pkg/depends/x/typesx" 9 ) 10 11 type MayValidator interface { 12 NewValidator(context.Context, typesx.Type) (validator.Validator, error) 13 } 14 15 type WithNamedByTag interface { 16 NamedByTag() string 17 } 18 19 func NewValidator( 20 ctx context.Context, 21 ft typesx.Type, 22 tags map[string]reflectx.StructTag, 23 omitempty bool, 24 tsfm Transformer, 25 ) (validator.Validator, error) { 26 if with, ok := tsfm.(WithNamedByTag); ok { 27 if tagKey := with.NamedByTag(); tagKey != "" { 28 ctx = validator.ContextWithTagKey(ctx, tagKey) 29 } 30 } 31 32 if t, ok := tsfm.(MayValidator); ok { 33 return t.NewValidator(ctx, ft) 34 } 35 36 compiler := validator.FactoryFromContext(ctx) 37 return compiler.Compile( 38 ctx, 39 []byte(tags[validator.TagValidate]), 40 ft, func(rule validator.Modifier) { 41 if omitempty { 42 rule.SetOptional(true) 43 } 44 if dftv, ok := tags[validator.TagDefault]; ok { 45 rule.SetDefaultValue([]byte(dftv)) 46 } 47 }, 48 ) 49 }