0

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.

Amanda
  • 2,013
  • 3
  • 24
  • 57
  • 2
    Use `required` in the validate tag, or the binding tag, as in many of the examples in gin's readme https://github.com/gin-gonic/gin – mkopriva Jan 27 '20 at 09:16
  • The `validate` tag isn't mentioned anywhere in the readme. Is this even using Gin's validation? It uses a completely different set of tags, according to the readme. – Adrian Jan 27 '20 at 14:44

0 Answers0