@@ -20,36 +20,35 @@ type CreditCardResult struct {
20
20
Brand string `json:"brand,omitempty"`
21
21
}
22
22
23
+ // Mapeamento de tipos para funções de validação
24
+ var validationFuncMap = map [string ]func (string ) (bool , string ){
25
+ "cpf" : func (value string ) (bool , string ) { return IsValidCPF (value ), "" },
26
+ "cnpj" : func (value string ) (bool , string ) { return IsValidCNPJ (value ), "" },
27
+ "url" : func (value string ) (bool , string ) { return IsValidURL (value ), "" },
28
+ "creditcard" : ValidateCreditCard ,
29
+ "email" : func (value string ) (bool , string ) { return IsValidEmail (value ), "" },
30
+ }
31
+
23
32
func ValidateHandler (c * gin.Context ) {
24
33
var req ValidationRequest
25
34
if err := c .ShouldBindJSON (& req ); err != nil {
26
35
c .JSON (http .StatusBadRequest , gin.H {"error" : err .Error ()})
27
36
return
28
37
}
29
38
39
+ validationFunc , exists := validationFuncMap [req .Type ]
40
+ if ! exists {
41
+ c .JSON (http .StatusBadRequest , gin.H {"error" : "Invalid validation type" })
42
+ return
43
+ }
44
+
30
45
var isValid bool
31
- var message string
32
46
var brand string
33
47
34
- switch req .Type {
35
- case "cpf" :
36
- isValid = IsValidCPF (req .Value )
37
- message = "CPF"
38
- case "cnpj" :
39
- isValid = IsValidCNPJ (req .Value )
40
- message = "CNPJ"
41
- case "url" :
42
- isValid = IsValidURL (req .Value )
43
- message = "URL"
44
- case "creditcard" :
45
- isValid , brand = ValidateCreditCard (req .Value )
46
- message = "Credit Card"
47
- case "email" :
48
- isValid = IsValidEmail (req .Value )
49
- message = "Email"
50
- default :
51
- c .JSON (http .StatusBadRequest , gin.H {"error" : "Invalid validation type" })
52
- return
48
+ if req .Type == "creditcard" {
49
+ isValid , brand = validationFunc (req .Value )
50
+ } else {
51
+ isValid , _ = validationFunc (req .Value )
53
52
}
54
53
55
54
var result interface {}
@@ -60,7 +59,7 @@ func ValidateHandler(c *gin.Context) {
60
59
}{
61
60
ValidationResult : ValidationResult {
62
61
IsValid : isValid ,
63
- Message : message ,
62
+ Message : req . Type ,
64
63
},
65
64
CreditCard : CreditCardResult {
66
65
Brand : brand ,
@@ -69,7 +68,7 @@ func ValidateHandler(c *gin.Context) {
69
68
} else {
70
69
result = ValidationResult {
71
70
IsValid : isValid ,
72
- Message : message ,
71
+ Message : req . Type ,
73
72
}
74
73
}
75
74
0 commit comments