登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-04-02 11:12:26 111浏览 收藏

golang学习网今天将给大家带来《为什么 post 请求在 gin golang 中不起作用?》,感兴趣的朋友请继续看下去吧!以下内容将会涉及到等等知识点,如果你是正在学习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,
    })
}

解决方案


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

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>