mirror of
https://github.com/gin-gonic/gin.git
synced 2025-10-14 12:12:12 +08:00
bindJSon的校验规则,待熟悉
This commit is contained in:
parent
b60fac92d9
commit
bf5f26cf33
@ -859,6 +859,10 @@ func (c *Context) ShouldBindWith(obj any, b binding.Binding) error {
|
|||||||
// ShouldBindWith for better performance if you need to call only once.
|
// ShouldBindWith for better performance if you need to call only once.
|
||||||
func (c *Context) ShouldBindBodyWith(obj any, bb binding.BindingBody) (err error) {
|
func (c *Context) ShouldBindBodyWith(obj any, bb binding.BindingBody) (err error) {
|
||||||
var body []byte
|
var body []byte
|
||||||
|
// This is the cache for the context of each request.
|
||||||
|
//There is no overwriting situation.
|
||||||
|
//If there is overwriting, it is also for the same request.
|
||||||
|
//Only the same context of the same request will be overwritten.
|
||||||
if cb, ok := c.Get(BodyBytesKey); ok {
|
if cb, ok := c.Get(BodyBytesKey); ok {
|
||||||
if cbb, ok := cb.([]byte); ok {
|
if cbb, ok := cb.([]byte); ok {
|
||||||
body = cbb
|
body = cbb
|
||||||
|
@ -10,6 +10,10 @@ import (
|
|||||||
type Body struct {
|
type Body struct {
|
||||||
// json tag to de-serialize json body
|
// json tag to de-serialize json body
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
|
//For example, you can use struct tags to validate a custom product code format. The validator package offers many helpful string validator helpers.
|
||||||
|
ProductCode string `json:"productCode" binding:"required,startswith=PC,len=10"`
|
||||||
|
StartDate string `json:"start_date" binding:"required" time_format:"2006-01-02"`
|
||||||
|
EndDate string `json:"end_date" binding:"required" time_format:"2006-01-02"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func UrlInit(router *gin.Engine) {
|
func UrlInit(router *gin.Engine) {
|
||||||
@ -98,7 +102,10 @@ func UrlInit(router *gin.Engine) {
|
|||||||
// BindJSON reads the body buffer to de-serialize it to a struct.
|
// BindJSON reads the body buffer to de-serialize it to a struct.
|
||||||
// BindJSON cannot be called on the same context twice because it flushes the body buffer.
|
// BindJSON cannot be called on the same context twice because it flushes the body buffer.
|
||||||
if err := c.ShouldBindBodyWith(&body, binding.JSON); err != nil {
|
if err := c.ShouldBindBodyWith(&body, binding.JSON); err != nil {
|
||||||
c.AbortWithError(http.StatusBadRequest, err)
|
c.AbortWithStatusJSON(http.StatusBadRequest,
|
||||||
|
gin.H{
|
||||||
|
"error": "VALIDATEERR-1",
|
||||||
|
"message": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
body2 := Body{}
|
body2 := Body{}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user