Go gin get request body json

Viewed 48168

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()
4 Answers

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 := ioutil.ReadAll(c.Request.Body)
if err != nil {
    // Handle error
}
err = client.Set("id", jsonData, 0).Err()

let's do it with an example. Assume your request body has user email like this:

{ email: "test@test.com" }

and now you want to get this email on the bakend. first define a struct like the following:

    type EmailRequestBody struct {
    Email string
    }

Now you can easily bind the email value in your request body to the struct you defined like the following: first define a variable for your struct like the following and then bind the value:

func ExampleFunction(c *gin.Context) {

var requestBody EmailRequestBody

   if err := c.BindJSON(&requestBody); err != nil {
       // DO SOMETHING WITH THE ERROR
   }

  fmt.Println(requestBody.Email)
}

you can easily access the email value and print it out or do whatever you need :

fmt.Println(requestBody.Email)

Or you can use GetRawData() function as:

jsonData, err := c.GetRawData()

if err != nil{
   //Handle Error
}

err = client.Set("id", jsonData, 0).Err()

If you want to get json body like other frameworks like express(Nodejs), you can do the following

bodyAsByteArray, _ := ioutil.ReadAll(c.Request.Body)
jsonBody := string(bodyAsByteArray)
Related