4

I'm trying to build a login API

type LoginRequest struct {
    Email    string `json:"email" binding:"required,email"`
    Password string `json:"password" binding:"required"`
}
func LoginHandler(app *config.Config) func(ctx *gin.Context) {
    return func(ctx *gin.Context) {
        var loginRequest LoginRequest
        if err := ctx.ShouldBindJSON(&loginRequest); err != nil {
            var ve validator.ValidationErrors
            if errors.As(err, &ve) {
                fmt.Println("validation error: ", ve)
                return
            }
            fmt.Printf("%T\n", err)
            fmt.Println("request content error: ", ve)
            return
        }
    }
}

and when I use curl as below:

curl --location --request POST '127.0.0.1:8080/api/login' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--data-raw '{
    "password": "password"
}'

I get output in the terminal as follows:

validator.ValidationErrors
request content error: 

despite the type of the variable loginRequest being validator.ValidationErrors, it couldn't be matched.

  • 1
    I'm not sure where validator.ValidationError is referenced from I think you should check like this ```errors.As(err, validator.ValidationErrors)``` – Zuko Sep 27 '22 at 22:09
  • 1
    Try explicitly asserting the type like `ve := err.(validator.ValidationErrors)` and see if that panics or not. If it panics - perhaps you have imported a different version (= different package) of `validator` than gin? Look at the last section of the import url. – Erwin Bolwidt Sep 28 '22 at 00:35
  • I solved it just by replacing `"github.com/go-playground/validator"` with `"github.com/go-playground/validator/v10"`. Thanks @ErwinBolwidt – ahmed mohamed Sep 28 '22 at 07:06

0 Answers0