gin采坑 用post application/json 请求 将requestBody绑定对象

 
 1 // 结构体字段名字和 json字段名不能一致
 2 
 3 type Test struct {
 4     Name string `form:"name" json:"name"`
 5     Age  int    `form:"age" json:"age"`
 6 }
 7 
 8 //新增文章标签
 9 func AddTag(c *gin.Context) {
10     var t Test
11 
12     if c.Bind(&t) == nil {
13         log.Println("====== Bind By Query String ======")
14         log.Println(t.Name)
15         log.Println(t.Age)
16     }
17 
18     if err := c.BindJSON(&t); err != nil {
19         c.String(http.StatusNotFound, `the body should be formA`)
20     }
21 
22     fmt.Println(t.Name)
23     c.String(http.StatusOK, `success`)
24 }

 

 

BindJson(json)、Bind(查询参数、formdata)

当我们 用post请求发送application/json 或者 formdata数据的时候,要想绑定到实体对象需要用到gin包的bind方法。

但这里有一个坑点,就是请求体json中字段的名字和  结构体中字段名字不能一样。

  

posted @ 2020-04-25 23:40  devhg  阅读(4242)  评论(0编辑  收藏  举报