Validation Number in Gin Golang

Viewed 75

I have an error when validating the number in gin, for the string data type there are no errors and they are detected, but when I fill in the price field of type int with a string, it gets an error of 500, I expect the error to be 400, what is the solution?

package web
type BookRequest struct{
    Title string `json:"title" binding:"required"`
    Description string `json:"description" binding:"required"`
    Price int `json:"price" binding:"required,numeric,gte=0"`
    Rating int `json:"rating" binding:"required,numeric"`
}
func (controller *BookControllerImpl) Create(ctx *gin.Context) {
    var bookRequest web.BookRequest

    err := ctx.ShouldBindJSON(&bookRequest)
    if err != nil {

        var error_request []string
        for _, e := range err.(validator.ValidationErrors) {
            errorMessage := fmt.Sprintf("Error field %s, Condition %s", e.Field(), e.ActualTag())
            error_request = append(error_request, errorMessage)
        }

        ctx.JSON(http.StatusBadRequest, web.WebResponse{
            Code:   http.StatusBadRequest,
            Status: "BAD REQUEST",
            Data:   error_request,
        })

        return
    }

    book, err := controller.BookService.Create(bookRequest)
    if err != nil {
        ctx.JSON(http.StatusBadRequest, web.WebResponse{
            Code:   http.StatusBadRequest,
            Status: "BAD REQUEST",
            Data:   err,
        })
    }

    ctx.JSON(http.StatusOK, web.WebResponse{
        Code:   200,
        Status: "Ok",
        Data:   book,
    })
}
1 Answers
  1. when I fill in the price field of type int with a string

If your request (payload Price) is not standart or it can be string or number, you can use json.Number type for your struct.

type BookRequest struct{
    Title string `json:"title" binding:"required"`
    Description string `json:"description" binding:"required"`
    Price json.Number `json:"price" binding:"required,numeric,gte=0"`
    Rating int `json:"rating" binding:"required,numeric"`
}

this is a simple example for json.Number : https://go.dev/play/p/7fyCFAon2PC

  1. You must check if err is an validator.ValidationErrors like this:
...
err := ctx.ShouldBindJSON(&bookRequest)
if err != nil {
    if vals, ok := err.(validator.ValidationErrors); ok {
        // do for loop from vals
        ...
        ctx.JSON(http.StatusBadRequest, web.WebResponse{
            Code:   http.StatusBadRequest,
            Status: "BAD REQUEST",
            Data:   error_request,
        })
        return
    }
    ctx.JSON(http.StatusInternalServerError, web.WebResponse{
        Code:   http.StatusInternalServerError,
        Status: "Internal Server Error",
        Data:   err,
    })
    return
}
...

========== Answer 2 ==========

You can implement json.Unmarshaller to do it

here's the example:

func (br *BookRequest) UnmarshalJSON(b []byte) error {

    // TODO: remove binding tag
    type helperBookRequest struct {
        Title       string `json:"title" binding:"required"`
        Description string `json:"description" binding:"required"`
        Price       any    `json:"price" binding:"required,numeric,gte=0"` // look at this type is any or interface{}
        Rating      int    `json:"rating" binding:"required,numeric"`
    }

    var hbr helperBookRequest

    err := json.Unmarshal(b, &hbr)
    if err != nil {
        return err
    }
    br.Title = hbr.Title
    br.Description = hbr.Description
    br.Rating = hbr.Rating

    switch hbr.Price.(type) {
    case float64:
        br.Price = strconv.Itoa(int(hbr.Price.(float64)))
    case string:
        br.Price = hbr.Price.(string)
    default:
        return errors.New("invalid type")
    }

    return nil
}

simple example in playground : https://go.dev/play/p/tmnKW4peBgp

Related