gin-gonic / gin

Gin is a HTTP web framework written in Go (Golang). It features a Martini-like API with much better performance -- up to 40 times faster. If you need smashing performance, get yourself some Gin.
https://gin-gonic.com/
MIT License
78.28k stars 7.99k forks source link

bindQuery and bindJSON all validate required, that can not work well for the same model. #2544

Open SeaJames opened 3 years ago

SeaJames commented 3 years ago

Description

when i use bindQuey, i hope the required validation method will not execute(because the required binding tag just for POST, not for query) , Or can gin let me call the validate method explicitly?

now when i call bindquery, it will raise required error because of the 'required' tag.

example:

package main

import ( "github.com/gin-gonic/gin" )

type User struct { Name string json:"name" binding: "required" Age int json: "age" binding: "required" }

func main() { g := gin.Default() g.GET("/hello?name=jack", func(c gin.Context) { var u User c.BindQuery(&u) }) g.POST("/hello", func(c gin.Context) { var u User
c.BindJSON(&u) } g.Run(":9000") }

Environment

Doarakko commented 3 years ago

@SeaJames As far as I can think of, there are two ways.

Example using validate package

package main

import (
    "net/http"

    "github.com/gin-gonic/gin"
    "github.com/go-playground/validator/v10"
)

type User struct {
    Name string `form:"name" json:"name" validate:"required"`
    Age  int    `form:"age" json:"age" validate:"required"`
}

func main() {
    g := gin.Default()

    g.GET("/hello", func(c *gin.Context) {
        var u User
        err := c.BindQuery(&u)
        if err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"message": "bind error"})
            return
        }

        c.JSON(http.StatusOK, gin.H{"message": "ok"})
    })

    g.POST("/hello", func(c *gin.Context) {
        var u User
        err := c.BindJSON(&u)
        if err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"message": "bind error"})
            return
        }

        validate := validator.New()
        err = validate.Struct(&u)
        if err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"message": "validate error"})
            return
        }

        c.JSON(http.StatusNoContent, nil)
    })

    g.Run(":9000")
}
SeaJames commented 3 years ago

wow, thanks for your reply. @Doarakko