我是靠谱客的博主 忧虑彩虹,这篇文章主要介绍gin 获取post请求的json body操作,现在分享给大家,希望可以做个参考。

我就废话不多说了,大家还是直接看代码吧~

代码如下

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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数据

第一种

复制代码
1
2
3
4
5
6
7
8
9
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"], }) }

第二种

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
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进行解析,不然会报错。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
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 } }

以上为个人经验,希望能给大家一个参考,也希望大家多多支持靠谱客。如有错误或未考虑完全的地方,望不吝赐教。

最后

以上就是忧虑彩虹最近收集整理的关于gin 获取post请求的json body操作的全部内容,更多相关gin内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(115)

评论列表共有 0 条评论

立即
投稿
返回
顶部