D
D
Dmitry Sviridov2020-04-22 01:54:17
go
Dmitry Sviridov, 2020-04-22 01:54:17

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

1 answer(s)
D
Dimonchik, 2020-04-22
@dimuska139

https://medium.com/@thedevsaddam/an-easy-way-to-va...
https://www.bookstack.cn/read/gin-en/model-binding...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question