-2

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?

Овов Очоы
  • 453
  • 1
  • 5
  • 12
  • 1
    `Request.Body` is an `io.Reader`. It has no public fields, so there is nothing for `json` to encode. – Adrian Aug 12 '21 at 18:55

1 Answers1

3

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.

Nick
  • 1,017
  • 1
  • 10
  • 16