"unexpected end of JSON input" 当在 POST 请求中传递对象数组时

"unexpected end of JSON input" when an array of objects is passed in POST request

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)
}

此代码片段在我传递 Json 对象 {"key":"value"} 时有效,但出现错误:

"unexpected end of JSON input"

当我传递像 [{"key":"val"},{"key": "val"}] 这样的数组作为输入时。

All GetRawData() does 是 return 流数据,因此不会导致您的错误:

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

但是,请尝试使用 BindJSON 并反序列化为结构。例如参见 [​​=14=].

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
    }
}