转投go系列-Gin框架-ShouldBind验证参数问题

今天发现前人(php转go的选手)的代码通过SholdBind方法不验证参数直接通过。严重怀疑代码使用方式不正确导致。

原来前人的代码是这么使用的 c.SholdBind…

func (con *Controller) Add(c *gin.Context) {
    
    
	var addReq *AddReq
	if err := c.ShouldBind(&addReq); err != nil {
    
    
		rsp.Errno = 0
		rsp.Errmsg = err.Error()
		c.JSON(http.StatusOK, rsp)
		return
	}
}
type AddReq struct {
    
    
	Name             string `form:"name" json:"name" binding:"required"`
	Comments         string `form:"comments" json:"comments"   binding:"-"`
}

当客户端传参数没有传name的时候,竟然奇迹般的验证通过了。
仔细观察传入addReq的参数是什么?是 **AddReq !!!

我们再看下validate源码

// ValidateStruct receives any kind of type, but only performed struct or pointer to struct type.
func (v *defaultValidator) ValidateStruct(obj interface{
    
    }) error {
    
    
	value := reflect.ValueOf(obj)
	valueType := value.Kind()
	if valueType == reflect.Ptr {
    
    
		valueType = value.Elem().Kind()
	}
	if valueType == reflect.Struct {
    
    
		v.lazyinit()
		if err := v.validate.Struct(obj); err != nil {
    
    
			return err
		}
	}
	return nil
}

人家说支持指针类型,可没说支持指针的指针啊!
所以正确的使用方式是下面的这样

func (con *Controller) Add(c *gin.Context) {
    
    
	addReq := AddReq{
    
    }
	if err := c.ShouldBind(&addReq); err != nil {
    
    
		rsp.Errno = 0
		rsp.Errmsg = err.Error()
		c.JSON(http.StatusOK, rsp)
		return
	}
}
type AddReq struct {
    
    
	Name             string `form:"name" json:"name" binding:"required"`
	Comments         string `form:"comments" json:"comments"   binding:"-"`
}

总之,发现整个项目都是这样,前人学艺不精啊!

Guess you like

Origin blog.csdn.net/lwcbest/article/details/120907935