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

原文来自:https://www.jb51.net/article/207614.htm

本文地址:https://www.linuxprobe.com/gin-post-json.html编辑:xiangping wu,审核员:逄增宝

Linux命令大全:https://www.linuxcool.com/

Linux系统大全:https://www.linuxdown.com/

红帽认证RHCE考试心得:https://www.rhce.net/