我们采用gin框架内置绑定操作进行模型绑定,常见方法分为俩类,一类是MustBind类,像Bind,BindJSON,BindQuery都是这一类,这一类绑定主要特征是一旦绑定失败则直接返回400错误;另一类绑定是ShouldBind类,像函数ShouldBind,ShouldBindJSON,ShouldBindQuery都是这一类,这一类绑定一旦失败,并不会立即响应400错误,而是将错误信息返回给上下文环境,开发者 需要自行处理。常见方法如下,实际上gin框架支持JSON 、XML、Form、Query、FormPost、FormMultipart 、ProtoBuf 、MsgPack等格式
ctx.ShouldBindJSON(&pageArg)
ctx.BindJSON(&pageArg)
ctx.ShouldBind(&pageArg)
ctx.BindWith(&pageArg,binding.JSON)
ctx.ShouldBindWith(&pageArg,binding.JSON)
下面我们演示数据绑定流程
1、 在model文件夹下定义PageArg结构体,注意其中如果需要绑定json数据则必须定义关于json的tag,如果需要绑定form表单类型的数据则需要定义包含form的tag
type PageArg struct {
Kword string `form:"kword"`
Datefrom time.Time `form:"datefrom" time_format:"2006-01-02 15:04:05"`
Dateto time.Time `form:"dateto" time_format:"2006-01-02 15:04:05"`
Pagesize int `form:"pagesize" json:"pagesize"`
Pagefrom int `form:"pagefrom" json:"pagefrom"`
Desc string `form:"desc" json:"desc"`
Asc string `form:"asc" json:"asc"`
}
2、 客户端发送json格式数据,注意必须使用"区分,另外JSON格式必须符合规范
//#curl -v -H "content-type:application/json" -d "{\"pagefrom\":1,\"pagesize\":20}" \ http://127.0.0.1/test/query
3、 服务器接收并进行数据处理返回数据
//定制路由映射绑定关系 func (ctrl *TestController)Router(router *gin.Engine){ r := router.Group("test").Use(ctrl.before()) r.Any("query",ctrl.query) } //实现绑定 func (ctrl *TestController)query(ctx *gin.Context){ var pageArg model.PageArg ctx.ShouldBindJSON(&pageArg) restgo.ResultOk(ctx,pageArg) }
系统返回结果如下
* Connected to 127.0.0.1 (127.0.0.1) port 80 (#0) > POST /test/query HTTP/1.1 > Host: 127.0.0.1 > User-Agent: curl/7.58.0 > Accept: */* > content-type:application/json > Content-Length: 28 > * upload completely sent off: 28 out of 28 bytes < HTTP/1.1 200 OK < Content-Type: application/json; charset=utf-8 < Date: Sun, 18 Feb 2018 06:38:39 GMT < Content-Length: 153 < {"code":200,"data":{"Kword":"","Datefrom":"0001-01-01T00:00:00Z","Dateto":"0001- 01-01T00:00:00Z","pagesize":20,"pagefrom":1,"desc":"","asc":""},"msg":""}
源代码获取地址 http://www.imwinlion.com