Use the binding package to automatically validate request data against a struct by defining validation tags on your fields. Define a struct with tags like required, min, or email, then pass it to c.ShouldBindJSON() to trigger validation and return errors if the data is invalid.
type LoginRequest struct {
Email string `json:"email" binding:"required,email"`
Password string `json:"password" binding:"required,min=6"`
}
func loginHandler(c *gin.Context) {
var req LoginRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
// Process valid request
}