Open SeaJames opened 3 years ago
@SeaJames As far as I can think of, there are two ways.
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")
}
wow, thanks for your reply. @Doarakko
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 intjson: "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