gin 獲取post請求的json body操作
更新時間:2021年03月15日 11:38:50 作者:風一樣的男子1
這篇文章主要介紹了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數(shù)據(jù)
第一種
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數(shù)據(jù)解析錯誤情況
byte數(shù)組接收網(wǎng)絡數(shù)據(jù)完網(wǎng)絡數(shù)據(jù)后,需要根據(jù)接收到的長度進行重新分片,才能被json進行解析,不然會報錯。
for {
len1, err := resp.Body.Read(data)
if len1 > 0 {
data1 := data[:len1] //需要根據(jù)接收到的長度進行重新分片
err1 := json.Unmarshal(data1, rec_rep)
if err1 != nil {
fmt.Println("json.Unmarshal failed")
}
}
if err != nil {
break
}
}
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。
相關文章
Golang異常處理之defer,panic,recover的使用詳解
這篇文章主要為大家介紹了Go語言異常處理機制中defer、panic和recover三者的使用方法,文中示例代碼講解詳細,需要的朋友可以參考下2022-05-05

