Search code examples
gohttp-post

Go gin get request body json


Im using postman to post data and in the body Im putting some simple json

Request Body

{
    "order":"1",
    "Name":"ts1"
}

I need to transfer the data to json and I try like following, and I wasnt able to get json, any idea what is missing

router.POST("/user", func(c *gin.Context) {
        var f interface{}
        //value, _ := c.Request.GetBody()
        //fmt.Print(value)

        err2 := c.ShouldBindJSON(&f)
        if err2 == nil {
            err = client.Set("id", f, 0).Err()
            if err != nil {
                panic(err)
            }

        }

The f is not a json and Im getting an error, any idea how to make it work? The error is:

redis: can't marshal map[string]interface {} (implement encoding.BinaryMarshaler)

I use https://github.com/go-redis/redis#quickstart

If I remove the the body and use hard-coded code like this I was able to set the data, it works

json, err := json.Marshal(Orders{
    order:   "1",
    Name: "tst",
})

client.Set("id", json, 0).Err()

Solution

  • If you only want to pass the request body JSON to Redis as a value, then you do not need to bind the JSON to a value. Read the raw JSON from the request body directly and just pass it through:

    jsonData, err := io.ReadAll(c.Request.Body)
    if err != nil {
        // Handle error
    }
    err = client.Set("id", jsonData, 0).Err()