0
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.

5
  • 3
    GetRawData doesn't do anything with json, it just reads the request's body, so that error that you quoted must come from code that you haven't shared. Commented Apr 19, 2019 at 10:33
  • Im sending the requests via Postman, using 'Raw' option under body Commented Apr 19, 2019 at 10:39
  • Is it set to JSON (application/json)? Commented Apr 19, 2019 at 10:44
  • 1
    @Neville what I'm trying to say is that GetRawData can't possibly return the error unexpected end of JSON input (unless you're using some other version of gin), that error is returned by encoding/json's decoder, which is never touched by GetRawData. So the handler code you've shared is irrelevant to the problem you have, the error is coming from somewhere else. Whether its a problem with Postman, or gin attempting to do some magic, or some middleware you may be using, I don't know however GetRawData it is not. Commented Apr 19, 2019 at 10:58
  • @mkopriva - Apologies, the problem occurred when I was doing a json.Unmarshall. Its solved now. Commented Apr 19, 2019 at 11:22

1 Answer 1

3

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
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.