gin
gin copied to clipboard
context.BindJSON does not respond with error message
Description
Based on the docs https://github.com/gin-gonic/gin#model-binding-and-validation I tried to use context.BindJSON
instead of c.ShouldBindJSON
. Unfortunately only c.ShouldBindJSON
responds with the error message.
How to reproduce
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
type MyStruct struct {
AField string `json:"aField" binding:"required"`
}
func main() {
r := gin.Default()
// This one only responds with a 400
r.POST("/foo", func(c *gin.Context) {
var ms MyStruct
err := c.BindJSON(&ms)
if err != nil {
return
}
c.JSON(http.StatusOK, "passes")
})
// This one responds with the error message
r.POST("/bar", func(c *gin.Context) {
var ms MyStruct
err := c.ShouldBindJSON(&ms)
if err != nil {
c.JSON(http.StatusBadRequest, err.Error())
return
}
c.JSON(http.StatusOK, "passes")
})
r.Run()
}
Expectations
Using Postman I would expect the following result from the endpoint /bar
Actual result
Instead I get a 400 but no error message
Environment
- go version: 1.18
- gin version (or commit ref): 1.8.1
- operating system: Linux
Looks like it is somehow connected to issue #622
https://github.com/gin-gonic/gin/issues/662
BindJSON returns "EOF"
Yeah, I have the same problem
Description
Based on the docs https://github.com/gin-gonic/gin#model-binding-and-validation I tried to use
context.BindJSON
instead ofc.ShouldBindJSON
. Unfortunately onlyc.ShouldBindJSON
responds with the error message.How to reproduce
package main import ( "net/http" "github.com/gin-gonic/gin" ) type MyStruct struct { AField string `json:"aField" binding:"required"` } func main() { r := gin.Default() // This one only responds with a 400 r.POST("/foo", func(c *gin.Context) { var ms MyStruct err := c.BindJSON(&ms) if err != nil { return } c.JSON(http.StatusOK, "passes") }) // This one responds with the error message r.POST("/bar", func(c *gin.Context) { var ms MyStruct err := c.ShouldBindJSON(&ms) if err != nil { c.JSON(http.StatusBadRequest, err.Error()) return } c.JSON(http.StatusOK, "passes") }) r.Run() }
Expectations
Using Postman I would expect the following result from the endpoint
/bar
Actual result
Instead I get a 400 but no error message
Environment
* go version: 1.18 * gin version (or commit ref): 1.8.1 * operating system: Linux
try this
r.POST("/bar", func(c *gin.Context) {
var ms MyStruct
err := c.ShouldBindJSON(&ms)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
// gin.H{}
//c.JSON(http.StatusBadRequest, err.Error())
return
}
c.JSON(http.StatusOK, "passes")
})
same with the doc : https://github.com/gin-gonic/gin#model-binding-and-validation