自定义验证方法(param_verify/product.go)
func NameValid ( v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string, ) bool { if s, ok := field.Interface().(string); ok { if s == "admin" { return false } } return true }
参数绑定(param_bind/product.go):
type ProductAdd struct { Name string `form:"name" json:"name" binding:"required,NameValid"` }
同时还要绑定验证器:
// 绑定验证器 if v, ok := binding.Validator.Engine().(*validator.Validate); ok { v.RegisterValidation("NameValid", param_verify.NameValid) }
咱们用 Postman 模拟 post 请求时,name 参数不传或传递为空,会出现:
Key: 'ProductAdd.Name' Error:Field validation for 'Name' failed on the 'required' tag
name=admin 时:
Key: 'ProductAdd.Name' Error:Field validation for 'Name' failed on the 'NameValid' tag
OK,上面两个验证都生效了!
上面的输出都是在控制台,能不能返回一个 Json 结构的数据呀?
能。接下来咱们制定 API 返回结构。
制定 API 返回结构
{ "code": 1, "msg": "", "data": null }
API 接口的返回的结构基本都是这三个字段。
比如 code=1 表示成功,code=-1 表示失败。
msg 表示提示信息。
data 表示返回的数据。
那么,我们怎么在 gin 框架中实现它?
其实很简单 基于 c.JSON() 方法进行封装即可,直接看代码。
package util import "github.com/gin-gonic/gin" type Gin struct { Ctx *gin.Context } type response struct { Code int `json:"code"` Message string `json:"msg"` Data interface{} `json:"data"` } func (g *Gin)Response(code 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 'NameValid' tag", "data": null }
OK,上面两个验证都生效了!
本文来自:51CTO博客
感谢作者:wx6087c7391d3cd
查看原文:[系列] - go-gin-api 规划目录和参数验证(二)
相关阅读 >>
手撸Golang 仿spring ioc/aop 之7 扫码2
更多相关阅读请进入《Go》频道 >>

Go语言101
一个与时俱进的Go编程知识库。