1

I am trying to write a rest endpoint using gin which should return status 200. I have coded it as well in the same way, but am getting status 400. My code is as follows:

router.POST("/parent", func(c *gin.Context) {
  var parent PARENT
  err := c.BindJSON(&parent)
  con,err := sql.Open("mysql", "myuser:mypass@/mydb")
  res,err := con.Exec(" insert into parent (username, mobile, email, password) values (?,?,?,?) ", parent.USERNAME, parent.MOBILE, parent.EMAIL, parent.PASSWORD)
  id,err := res.LastInsertId()
  if err != nil {
    con.Close()
  }
  c.JSON(200, gin.H{"success" : 1, "userid" : id})
  return
})

I am always getting this in gin logs:

[GIN-debug] [WARNING] Headers were already written. Wanted to override status code 400 with 200

Any idea what am I missing. Thanks

0

1 Answer 1

2

Probably c.BindJSON() errors because of invalid input (try to add some log message there to see what's wrong) and that sets 400 status and writes headers. Since code does not terminate there (there's no return) it continues to c.JSON(200, ...) and tries to overwrite already written headers with 200.

err := c.BindJSON(&parent)
if err != nil {
    log.Println(err)
    return
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.