如何从 Gin 中发布的 JSON 获取特定参数?

How to get specific param from posted JSON in Gin?

我需要从发布的 json 中获取一个参数。 而且我不想只为此制作结构。 这是我试过的

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

请求的Json数据有许多其他字段,包括价格

{
   ...other fields
   price: 30
}

但是这个work.I不认为是因为我绑定了两次,我如何绑定多次才能成功?

谢谢

尝试使用ShouldBindJSONBindJSON 正在读取正文,因此如果多次读取上下文正文,我们将处于 EOF

ShouldBindJSON将request body存入context中,再次调用时复用