如何使用 Gin-Gonic 在 Go 中读取 snake case JSON 请求正文
How to read snake case JSON request body in Go using Gin-Gonic
我正在使用 gin-gonic to create my first 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
的值为""
。但是当我 post 我的请求正文为
{
"firstName" : "James Bond"
}
user.FirstName
的值为"James Bond"
。
如何将 JSON 请求主体中的 snake case 变量 "first_name"
映射到结构中的相应变量?我错过了什么吗?
您有错字(json: "first_name"
中的 space)。
应该是:
type User struct {
FirstName string `json:"first_name"`
}
我正在使用 gin-gonic to create my first 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
的值为""
。但是当我 post 我的请求正文为
{
"firstName" : "James Bond"
}
user.FirstName
的值为"James Bond"
。
如何将 JSON 请求主体中的 snake case 变量 "first_name"
映射到结构中的相应变量?我错过了什么吗?
您有错字(json: "first_name"
中的 space)。
应该是:
type User struct {
FirstName string `json:"first_name"`
}