I'm using Go 1.17 with Gin and I want to implement a struct validation before sending the data to my database. I took the example from Gin documentation.
In the struct we can declare different tags to validate a field like this:
type User struct {
FirstName string `json:"first_name" binding:"required"`
LastName string `json:"last_name" binding:"required"`
Age uint8 `json:"age" binding:"gte=0,lte=130"`
Email string `json:"email" binding:"required,email"`
FavouriteColor string `json:"favourite_color" binding:"iscolor"`
}
And in the handler I can grab the error like this:
var u User
if err := c.ShouldBindWith(&u, binding.Query); err == nil {
c.JSON(http.StatusOK, gin.H{"message": "Good Job"})
} else {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
}
The error message will be:
{
"error": "Key: 'User.FirstName' Error:Field validation for 'FirstName' failed on the 'required' tag\nKey: 'User.LastName' Error:Field validation for 'LastName' failed on the 'required' tag\nKey: 'User.Email' Error:Field validation for 'Email' failed on the 'required' tag\nKey: 'User.FavouriteColor' Error:Field validation for 'FavouriteColor' failed on the 'iscolor' tag"
}
The error messages are too verbose how it's possible to returns a better error to the user? I'd like to model the json response like:
{
"errors": [
"first_name": "This field is required",
"last_name": "This field is required",
"age": "This field is required",
"email": "Invalid email"
]
}