Search code examples
gogo-gin

How do I get the body that was sent? Using gin gonic


How do I get the body that was sent?

package main

import (
  "fmt"
  "github.com/gin-gonic/gin"
)
func main()  {
  fmt.Println("Hello, world!")
  r := gin.Default()
  r.POST("/", func(c *gin.Context) {
    body := c.Request.Body
    c.JSON(200,body);
  })
  r.Run(":8080");
}

I make a request via postman

  {
         "email": "test@gmail.com",
         "password": "test"
    }

and in response I get empty json {} what to do?


Solution

  • You can bind the incoming request json as follows:

    package main
    
    import (
        "github.com/gin-gonic/gin"
    )
    
    type LoginReq struct {
        Email    string
        Password string
    }
    
    func main() {
        r := gin.Default()
    
        r.POST("/", func(c *gin.Context) {
            var req LoginReq
            c.BindJSON(&req)
            c.JSON(200, req)
        })
        r.Run(":8080")
    }
    

    Remember this method gives 400 if there is a binding error. If you want to handle error yourself, try ShouldBindJSON which returns an error if any or nil.