📊 Capítulo 03: Data Binding & Validação
Especialização Backend com Go & Gin Gonic
🗺️ O Ciclo de Data Binding e Validação de DTOs
flowchart LR
REQ["HTTP Request (JSON / Form / Query)"]
--> BIND["c.ShouldBindJSON(&dto) / c.ShouldBindQuery(&dto)"]
--> TAGS["Leitura de Struct Tags (`json:... binding:...`)"]
--> VALID["Validador go-playground/validator/v10"]
--> CHECK{"Válido?"}
CHECK -- "SIM" --> SUCCESS["Processa Dados com Tipagem Segura"]
CHECK -- "NÃO" --> ERR["HTTP 400 Bad Request com Detalhes dos Campos"]
style REQ fill:#ede7f6,stroke:#512da8,stroke-width:2px
style BIND fill:#fff3e0,stroke:#ff9800,stroke-width:2px
style TAGS fill:#e1f5fe,stroke:#03a9f4,stroke-width:1.5px
style VALID fill:#e8f5e9,stroke:#4caf50,stroke-width:2px
style SUCCESS fill:#c8e6c9,stroke:#2e7d32,stroke-width:2px
style ERR fill:#ffebee,stroke:#d32f2f,stroke-width:2px
🎯 Slide 1: ShouldBindJSON vs BindJSON
-
c.BindJSON(&dto): Se houver erro, responde automaticamente com HTTP 400 e escreve no cabeçalho (pouco customizável). c.ShouldBindJSON(&dto)(Padrão Corporativo): Retorna oerrorpara você tratar, permitindo customizar a mensagem de resposta em JSON padronizado.
🎯 Slide 2: Struct Tags de Validação Poderosas
type CriarUsuarioDTO struct {
Nome string `json:"nome" binding:"required,min=3,max=100"`
Email string `json:"email" binding:"required,email"`
Idade int `json:"idade" binding:"gte=18,lte=120"`
Preco float64 `json:"preco" binding:"gt=0"`
}
🎯 Slide 3: Validadores Customizados Registrados
- Permite registrar funções de validação de regras de negócio complexas (ex.: validação de CPF/CNPJ brasileiro) diretamente no motor do validador do Gin!
Slide 1 de 1
Atalhos: ← → Navegar • Espaço Avançar • F Tela Cheia • Home Início • End Fim