e int, msg string, data interface{}) {
g.Ctx.JSON(200, response{
Code : code,
Message : msg,
Data : data,
})
return
}
控制器调用(controller/product.go):
utilGin := util.Gin{Ctx:c}
if err := c.ShouldBind(¶m_bind.ProductAdd{}); err != nil {
utilGin.Response(-1, err.Error(), nil)
return
}
咱们用 Postman 模拟 post 请求时,name 参数不传或传递为空,会出现:
{
"code": -1,
"msg": "Key: 'ProductAdd.Name' Error:Field validation for 'Name' failed on the 'required' tag",
"data": null
}
name=admin 时:
{
"code": -1,
"msg": "Key: 'ProductAdd.Name' Error:Field validation for 'Name' failed on the 'Nameva lid' tag",
"data": null
}
OK,上面两个验证都生效了!
源码地址
https://github.com/xinliangnote/go-gin-api
go-gin-api 系列文章