为了账号安全,请及时绑定邮箱和手机立即绑定

为什么 post 请求在 gin golang 中不起作用?

为什么 post 请求在 gin golang 中不起作用?

Go
胡子哥哥 2023-03-29 15:29:46
这段代码不起作用,响应将是空的,就像这样{"test":""}。    func main() {            router := gin.Default()            router.POST("/test", func(c *gin.Context) {            test := c.Query("test")            c.JSON(200, gin.H{                "test": test,            })        })        router.Run()    }更新:我通过结构找到了简单的解决方案:func test(c *gin.Context) {    test := struct {        Test   string `json:"test"`        Test2 string `json:"test2"`    }{}    c.BindJSON(&test)    c.JSON(200, gin.H{        "test1":  test.Test,        "test2": test.Test2,    })}
查看完整描述

2 回答

?
慕沐林林

TA贡献2016条经验 获得超9个赞

func test(c *gin.Context) {

    test := struct {

        Test   string `json:"test"`

        Test2 string `json:"test2"`

    }{}

    c.BindJSON(&test)


    c.JSON(200, gin.H{

        "test1":  test.Test,

        "test2": test.Test2,

    })

}


查看完整回答
反对 回复 2023-03-29
?
守着星空守着你

TA贡献1799条经验 获得超8个赞

您将数据作为正文发送,您应该将正文绑定到一个变量以访问它。


type Data struct {

   test string

}

// ...


router.POST("/test", func(c *gin.Context) {

   var data Data        

   c.BindJSON(&data)


   c.JSON(200, gin.H{ 

      "test": data.test,

   })

})


查看完整回答
反对 回复 2023-03-29
  • 2 回答
  • 0 关注
  • 81 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信