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

这段代码不起作用,响应将是空的,就像这样{"test":""}。


    func main() {

            router := gin.Default()


            router.POST("/test", f


unc(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,

    })

}


胡子哥哥
浏览 83回答 2
2回答

慕沐林林

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

守着星空守着你

您将数据作为正文发送,您应该将正文绑定到一个变量以访问它。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,   })})
打开App,查看更多内容
随时随地看视频慕课网APP