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 安装powerbuilder10卡在安装程序正在运行这个页面 没有下一步任何指令
  • ¥15 关于mpi的问题:请问遇到这种情况需要怎么解决,出现这个问题后电脑不能进行mpi多核运行只能进行单核运行
  • ¥50 微信聊天记录备份到电脑提示成功了,但还是没同步到电脑微信
  • ¥15 python怎么在已有视频文件后添加新帧
  • ¥20 虚幻UE引擎如何让多个同一个蓝图的NPC执行一样的动画,
  • ¥15 fluent里模拟降膜反应的UDF编写
  • ¥15 MYSQL 多表拼接link
  • ¥15 关于某款2.13寸墨水屏的问题
  • ¥15 obsidian的中文层级自动编号
  • ¥15 同一个网口一个电脑连接有网,另一个电脑连接没网