使用GIN框架编写的Go REST API 返回状态码400。

huangapple go评论72阅读模式
英文:

Go rest api using GIN Framework returning status code 400

问题

我正在尝试使用gin编写一个REST端点,应该返回状态码200。我已经按照相同的方式编码了,但是得到的状态码是400。我的代码如下:

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
})

我在gin日志中始终得到以下信息:

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

有任何想法我可能遗漏了什么。谢谢。

英文:

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

答案1

得分: 2

可能是因为无效的输入导致了c.BindJSON()的错误(尝试添加一些日志消息以查看问题所在),这会设置400状态并写入标头。由于代码在此处没有终止(没有return),它会继续执行c.JSON(200, ...),并尝试用200覆盖已经写入的标头。

err := c.BindJSON(&parent)
if err != nil {
    log.Println(err)
    return
}
英文:

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
}

huangapple
  • 本文由 发表于 2022年5月13日 10:24:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/72223833.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定