Answer the question
In order to leave comments, you need to log in
How to do validation in Go?
How to validate a GET parameter? If you specify a number in page_size, then everything is fine: /articles?page_size=10 . But if you pass the string /articles?page_size=test , then everything goes into panic, and such an error cannot be handled. You can change PageSize from int to string, but then the min validation rule does not work (because min for strings is a string length validation). How do you deal with such situations in Go?
package main
import (
"github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10"
"net/http"
"reflect"
)
func main() {
g := gin.Default()
g.GET("/articles", func(c *gin.Context) {
type Paginator struct {
PageSize int `form:"page_size" binding:"required,min=1"`
}
var pag Paginator
if err := c.ShouldBindQuery(&pag); err != nil {
errs := err.(validator.ValidationErrors)
respErrors := make(map[string]interface{})
for _, v := range errs {
field, _ := reflect.TypeOf(&pag).Elem().FieldByName(v.Field())
fieldName, _ := field.Tag.Lookup("form")
respErrors[fieldName] = v.Tag()
}
c.JSON(http.StatusBadRequest, gin.H{"errors": respErrors})
return
}
c.String(200, "Articles list is here")
})
g.Run(":9000")
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question