bindJSon的校验规则,待熟悉

This commit is contained in:
flybread 2025-06-05 11:39:20 +08:00
parent b60fac92d9
commit bf5f26cf33
2 changed files with 12 additions and 1 deletions

View File

@ -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

View File

@ -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{}