gin 获取post请求的json body操作
我就废话不多说了,大家还是直接看代码吧~
代码如下
typeKDRespBodystruct{
Errcodeint`json:"errcode"`
Descstring`json:"description"`
Data[]services.KdSearchBack`json:"data"`
}
varreqInfoKDRespBody
err:=c.BindJSON(&reqInfo)
iferr!=nil{
log.Info(err)
c.JSON(200,gin.H{"errcode":400,"description":"PostDataErr"})
return
}else{
fmt.Println(reqInfo.Data)
}
补充:使用gin接受post的json数据
第一种
funcLogin(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"],
})
}
第二种
typeUserstruct{
Namestring`json:"name"`
Passwordint64`json:"password"`
}
funcLogin(c*gin.Context){
json:=User{}
c.BindJSON(&json)
log.Printf("%v",&json)
c.JSON(http.StatusOK,gin.H{
"name":json.Name,
"password":json.Password,
})
}
补充:golangjson数据解析错误情况
byte数组接收网络数据完网络数据后,需要根据接收到的长度进行重新分片,才能被json进行解析,不然会报错。
for{
len1,err:=resp.Body.Read(data)
iflen1>0{
data1:=data[:len1]//需要根据接收到的长度进行重新分片
err1:=json.Unmarshal(data1,rec_rep)
iferr1!=nil{
fmt.Println("json.Unmarshalfailed")
}
}
iferr!=nil{
break
}
}
以上为个人经验,希望能给大家一个参考,也希望大家多多支持毛票票。如有错误或未考虑完全的地方,望不吝赐教。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。