rest - 如何使用 Gin-Gonic 在 Go 中读取 snake case JSON 请求体

标签 rest go go-gin

我正在使用 gin-gonic创建我的第一个Go休息 API 服务器。

我的User结构如下

type User struct {
    FirstName string `json: "first_name"`
}

我的代码中定义了以下路由

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

        var user request_parameters.User
        c.BindJSON(&user)

        //some code here

        c.JSON(http.StatusOK, token)
})

我的POST请求体如下

{
    "first_name" : "James Bond"
}

在这种情况下,user.FirstName 的值为 ""。但是当我将我的请求正文发布为

{
    "firstName" : "James Bond"
}

user.FirstName 的值为 "James Bond"

如何将 JSON 请求正文中的蛇形变量 "first_name" 映射到结构中的相应变量?我错过了什么吗?

最佳答案

您有错字(json: "first_name" 中的空格)。

应该是:

type User struct {
    FirstName string `json:"first_name"`
}

关于rest - 如何使用 Gin-Gonic 在 Go 中读取 snake case JSON 请求体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54703311/

相关文章:

java - 基于 Jersey 的 RESTful 服务报告进度

javascript - 在 Firebase 的不同节点中写入多个对象

go - 将 map[string]SpecificType 与 map[string]SomeInterface 方法一起使用

go - 我如何使用 channel 来知道循环启动的所有 goroutines 何时完成

postgresql - 如何在 gorm 中为 Association 请求主体属于并拥有一个

postgresql - pq : password authentication failed for user "user-name" while accessing postgres in vscode

java - 当 GET 也可以充当 POST 时,为什么我们需要 RestFul 中的 GET 和 POST 方法

javascript - 如何从客户端安全地发送密码?

Emacs 在 go-mode 下找不到 gofmt

go - 有什么解决方案可以在 Gin 中呈现这样的 html 吗?