今天发现前人(php转go的选手)的代码通过SholdBind方法不验证参数直接通过。严重怀疑代码使用方式不正确导致。
原来前人的代码是这么使用的 c.SholdBind…
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14func (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源码
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16// 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 }
人家说支持指针类型,可没说支持指针的指针啊!
所以正确的使用方式是下面的这样
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14func (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:"-"` }
总之,发现整个项目都是这样,前人学艺不精啊!
最后
以上就是彩色哑铃最近收集整理的关于转投go系列-Gin框架-ShouldBind验证参数问题的全部内容,更多相关转投go系列-Gin框架-ShouldBind验证参数问题内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复