github.com/mundipagg/boleto-api@v0.0.0-20230620145841-3f9ec742599f/models/validator.go (about) 1 package models 2 3 //Validator estrutura de validação 4 type Validator struct { 5 Rules []Rule 6 } 7 8 //Rule é a regra que será adiciona a camada de validação 9 type Rule func(interface{}) error 10 11 //Push insere no Validator uma nova regra 12 func (v *Validator) Push(r Rule) { 13 v.Rules = append(v.Rules, r) 14 } 15 16 //Assert aplica todas as validações no objeto passado como parâmetro 17 func (v *Validator) Assert(o interface{}) Errors { 18 errs := NewErrors() 19 for _, assert := range v.Rules { 20 err := assert(o) 21 switch t := err.(type) { 22 case ErrorResponse: 23 errs = append(errs, t) 24 default: 25 if err != nil { 26 errs.Append(err.Error(), "Erro interno") 27 } 28 } 29 } 30 return errs 31 } 32 33 //NewValidator retorna nova instância de validação 34 func NewValidator() *Validator { 35 return &Validator{} 36 }