共计 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} | |
} |
正文完
星哥玩云-微信公众号
