阿里云-云小站(无限量代金券发放中)
【腾讯云】云服务器、云数据库、COS、CDN、短信等热卖云产品特惠抢购

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

69次阅读
没有评论

共计 1067 个字符,预计需要花费 3 分钟才能阅读完成。

导读 本文主要介绍了 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}
}

阿里云 2 核 2G 服务器 3M 带宽 61 元 1 年,有高配

腾讯云新客低至 82 元 / 年,老客户 99 元 / 年

代金券:在阿里云专用满减优惠券

正文完
星哥说事-微信公众号
post-qrcode
 0
星锅
版权声明:本站原创文章,由 星锅 于2024-07-25发表,共计1067字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
【腾讯云】推广者专属福利,新客户无门槛领取总价值高达2860元代金券,每种代金券限量500张,先到先得。
阿里云-最新活动爆款每日限量供应
评论(没有评论)
验证码
【腾讯云】云服务器、云数据库、COS、CDN、短信等云产品特惠热卖中