Skip to content

Commit

Permalink
Merge pull request #6 from gatinhodev/features
Browse files Browse the repository at this point in the history
change switch case to maps
  • Loading branch information
dennersousa authored Feb 11, 2024
2 parents b1818af + e38890b commit e0c9c75
Showing 1 changed file with 21 additions and 22 deletions.
43 changes: 21 additions & 22 deletions validate/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,36 +20,35 @@ type CreditCardResult struct {
Brand string `json:"brand,omitempty"`
}

// Mapeamento de tipos para funções de validação
var validationFuncMap = map[string]func(string) (bool, string){
"cpf": func(value string) (bool, string) { return IsValidCPF(value), "" },
"cnpj": func(value string) (bool, string) { return IsValidCNPJ(value), "" },
"url": func(value string) (bool, string) { return IsValidURL(value), "" },
"creditcard": ValidateCreditCard,
"email": func(value string) (bool, string) { return IsValidEmail(value), "" },
}

func ValidateHandler(c *gin.Context) {
var req ValidationRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}

validationFunc, exists := validationFuncMap[req.Type]
if !exists {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid validation type"})
return
}

var isValid bool
var message string
var brand string

switch req.Type {
case "cpf":
isValid = IsValidCPF(req.Value)
message = "CPF"
case "cnpj":
isValid = IsValidCNPJ(req.Value)
message = "CNPJ"
case "url":
isValid = IsValidURL(req.Value)
message = "URL"
case "creditcard":
isValid, brand = ValidateCreditCard(req.Value)
message = "Credit Card"
case "email":
isValid = IsValidEmail(req.Value)
message = "Email"
default:
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid validation type"})
return
if req.Type == "creditcard" {
isValid, brand = validationFunc(req.Value)
} else {
isValid, _ = validationFunc(req.Value)
}

var result interface{}
Expand All @@ -60,7 +59,7 @@ func ValidateHandler(c *gin.Context) {
}{
ValidationResult: ValidationResult{
IsValid: isValid,
Message: message,
Message: req.Type,
},
CreditCard: CreditCardResult{
Brand: brand,
Expand All @@ -69,7 +68,7 @@ func ValidateHandler(c *gin.Context) {
} else {
result = ValidationResult{
IsValid: isValid,
Message: message,
Message: req.Type,
}
}

Expand Down

0 comments on commit e0c9c75

Please sign in to comment.