'Go rest api using GIN Framework returning status code 400
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
Solution 1:[1]
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
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |