您当前的位置: 首页 >  json

Linux小百科

暂无认证

  • 0浏览

    0关注

    1185博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

gin 获取post请求的json body操作详解

Linux小百科 发布时间:2021-05-15 23:39:09 ,浏览量:0

本文主要介绍了gin 获取post请求的json body操作

代码如下

type KDRespBody struct {
   Errcode int `json:"errcode"`
   Desc string `json:"description"`
   Data []services.KdSearchBack `json:"data"`
}
var reqInfo KDRespBody
err := c.BindJSON(&reqInfo)
if err != nil {
   log.Info(err)
   c.JSON(200, gin.H{"errcode": 400, "description": "Post Data Err"})
   return
} else {
  fmt.Println(reqInfo.Data)
}

补充:使用gin接受post的json数据

第一种

func Login(c *gin.Context) {
 json := make(map[string]interface{}) //注意该结构接受的内容
 c.BindJSON(&json)
 log.Printf("%v",&json)
 c.JSON(http.StatusOK, gin.H{
 "name": json["name"],
 "password": json["password"],
 })
}

第二种

type User struct {
 Name string `json:"name"`
 Password int64 `json:"password"`
}
func Login(c *gin.Context) {
 json := User{}
 c.BindJSON(&json)
 log.Printf("%v",&json)
 c.JSON(http.StatusOK, gin.H{
 "name": json.Name,
 "password": json.Password,
 })
}

补充:golang json数据解析错误情况

byte数组接收网络数据完网络数据后,需要根据接收到的长度进行重新分片,才能被json进行解析,不然会报错。

  for {
 len1, err := resp.Body.Read(data)
 if len1 > 0 {
 data1 := data[:len1] //需要根据接收到的长度进行重新分片
 err1 := json.Unmarshal(data1, rec_rep)
 if err1 != nil {
  fmt.Println("json.Unmarshal failed")
 }
 }
 if err != nil {
 break
 }
}
关注
打赏
1665632672
查看更多评论
立即登录/注册

微信扫码登录

0.0403s