skip to Main Content

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


  1. 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()
    
    Login or Signup to reply.
  2. Or you can use GetRawData() function as:

    jsonData, err := c.GetRawData()
    
    if err != nil{
       //Handle Error
    }
    
    err = client.Set("id", jsonData, 0).Err()
    
    Login or Signup to reply.
  3. let’s do it with an example. Assume your request body has a user email like this:

    { email: "[email protected]" }
    

    and now you want to get this email on the back-end. 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: first, define a variable for your struct 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)
    
    Login or Signup to reply.
  4. 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)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search