I need to get one param from posted json. And I don't want to make struct for only this. This is what I have tried
type NewTask struct {
Price uint64 `json:"price"`
}
func (pc TaskController) Create(c *gin.Context) {
var service Service
if err := c.BindJSON(&service); err != nil {
log.Println(err) // this works
}
var u NewTask
if err := c.BindJSON(&u); err != nil {
log.Println(err) // this return EOF error
}
fmt.Println(u.Price)
}
Requested Json data have many other fields including price
{
...other fields
price: 30
}
But this don't work.I think its because I am binding twice, How can I success in binding multiple?
Thanks
Try to use ShouldBindJSON
. The BindJSON
is reading the body, so we are at EOF
if the context Body get read multiple times.
ShouldBindJSON
stores the request body into the context, and reuse when it is called again.