Skip to content

Commit e0c9c75

Browse files
authored
Merge pull request #6 from gatinhodev/features
change switch case to maps
2 parents b1818af + e38890b commit e0c9c75

File tree

1 file changed

+21
-22
lines changed

1 file changed

+21
-22
lines changed

validate/api.go

Lines changed: 21 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -20,36 +20,35 @@ type CreditCardResult struct {
2020
Brand string `json:"brand,omitempty"`
2121
}
2222

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+
2332
func ValidateHandler(c *gin.Context) {
2433
var req ValidationRequest
2534
if err := c.ShouldBindJSON(&req); err != nil {
2635
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
2736
return
2837
}
2938

39+
validationFunc, exists := validationFuncMap[req.Type]
40+
if !exists {
41+
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid validation type"})
42+
return
43+
}
44+
3045
var isValid bool
31-
var message string
3246
var brand string
3347

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)
5352
}
5453

5554
var result interface{}
@@ -60,7 +59,7 @@ func ValidateHandler(c *gin.Context) {
6059
}{
6160
ValidationResult: ValidationResult{
6261
IsValid: isValid,
63-
Message: message,
62+
Message: req.Type,
6463
},
6564
CreditCard: CreditCardResult{
6665
Brand: brand,
@@ -69,7 +68,7 @@ func ValidateHandler(c *gin.Context) {
6968
} else {
7069
result = ValidationResult{
7170
IsValid: isValid,
72-
Message: message,
71+
Message: req.Type,
7372
}
7473
}
7574

0 commit comments

Comments
 (0)