From bf5f26cf3319c80f62098f6e1c1b0f8d45593d9b Mon Sep 17 00:00:00 2001 From: flybread <1015126672@qq.com> Date: Thu, 5 Jun 2025 11:39:20 +0800 Subject: [PATCH] =?UTF-8?q?bindJSon=E7=9A=84=E6=A0=A1=E9=AA=8C=E8=A7=84?= =?UTF-8?q?=E5=88=99=EF=BC=8C=E5=BE=85=E7=86=9F=E6=82=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- context.go | 4 ++++ examples/url/ini/utl_gin.go | 9 ++++++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/context.go b/context.go index d949ccda..eabdb270 100644 --- a/context.go +++ b/context.go @@ -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. func (c *Context) ShouldBindBodyWith(obj any, bb binding.BindingBody) (err error) { 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 cbb, ok := cb.([]byte); ok { body = cbb diff --git a/examples/url/ini/utl_gin.go b/examples/url/ini/utl_gin.go index db92b0c2..649ab628 100644 --- a/examples/url/ini/utl_gin.go +++ b/examples/url/ini/utl_gin.go @@ -10,6 +10,10 @@ import ( type Body struct { // json tag to de-serialize json body 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) { @@ -98,7 +102,10 @@ func UrlInit(router *gin.Engine) { // 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. 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 } body2 := Body{}