Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go gin get request body json

Tags:

http-post

go

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()
like image 600
Beno Odr Avatar asked May 20 '20 18:05

Beno Odr


2 Answers

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

{ email: "[email protected]" }

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)
like image 50
Ali Bayatpour Avatar answered Sep 18 '22 08:09

Ali Bayatpour


Or you can use GetRawData() function as:

jsonData, err := c.GetRawData()

if err != nil{
   //Handle Error
}

err = client.Set("id", jsonData, 0).Err()
like image 35
mwangox Avatar answered Sep 21 '22 08:09

mwangox