druzuz321103 2019-06-27 02:06 采纳率: 100%
浏览 1367
已采纳

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

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

  • 写回答

1条回答 默认 最新

  • douyao1856 2019-06-27 05:42
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器