I am using gin for creating a http server. I want to validate each and every HTTP request before I start calling my other functions.
I created a following struct
named CreateUser
to validate all incoming HTTP POST requests for CreateUser
type CreateUser struct {
FirstName string `validate:"min:2, regexp=^[a-zA-Z]*$"`
LastName string `validate:"min:2, regexp=^[a-zA-Z]*$"`
Email string `validate:"min:10, max=255 regexp=^[0-9a-zA-Z]*@[a-z]*$"`
}
The following function gets called when a request for UserCreate
happens. But even if I do not send the firstName
in the post request. The validation passes without an error. What could be the reason for this? How could I validate each and every HTTP request for it schema?
func (uhc UserHttpController) UserCreate(ctx *gin.Context) {
var createUser config.CreateUser
if err := ctx.BindJSON(&createUser); err != nil {
// send the bad request response
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
createdUser := InitUserController(uhc.globalVars).UserCreate(createUser)
ctx.JSON(http.StatusOK, gin.H{
"data": createdUser,
})
}
I tried without sending lastName
in POST request body but on debugging the LastName
is initialized to ""
empty string and thus no error occurs.