duanmaifu3428 2019-04-19 10:24
浏览 736
已采纳

Golang的Gin框架在发布请求中传递了一系列json对象时出现问题

import "github.com/gin-gonic/gin"

func Receive(c *gin.Context) {
  // Gets JSON ecnoded data
  rawData, err := c.GetRawData()
  if err != nil {
      return nil, err
  }

  logger.Info("Raw data received - ", rawData)
}

This code snippet works when I pass a Json object {"key":"value"} but gives an error - "unexpected end of JSON input" when I pass an array like - [{"key":"val"},{"key": "val"}] as the input.

Any help on this would be appreciated.

  • 写回答

1条回答 默认 最新

  • dpdfh60088 2019-04-19 10:43
    关注

    All GetRawData() does is return stream data, so that shouldn't cause your error:

    // GetRawData return stream data.
    func (c *Context) GetRawData() ([]byte, error) {
        return ioutil.ReadAll(c.Request.Body)
    }
    

    However, try using BindJSON and deserialise into a struct. See for example this question.

    type List struct {
        Messages []string `key:"required"`
    }
    
    func Receive(c *gin.Context) {
        data := new(List)
        err := c.BindJSON(data)
        if err != nil {
            return nil, err
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 微信聊天记录备份到电脑提示成功了,但还是没同步到电脑微信
  • ¥15 python怎么在已有视频文件后添加新帧
  • ¥20 虚幻UE引擎如何让多个同一个蓝图的NPC执行一样的动画,
  • ¥15 fluent里模拟降膜反应的UDF编写
  • ¥15 MYSQL 多表拼接link
  • ¥15 关于某款2.13寸墨水屏的问题
  • ¥15 obsidian的中文层级自动编号
  • ¥15 同一个网口一个电脑连接有网,另一个电脑连接没网
  • ¥15 神经网络模型一直不能上GPU
  • ¥20 wpf datagrid单元闪烁效果失灵