奇怪的是,http /GET请求在我的代码中返回空JSON (用于GET)或添加空结构(用于POST),这里是代码片段
package main
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
)
type employee struct {
id int64 `json:"id" binding:"required"`
}
var all_employee = []employee{
{id: 1},
}
func getEmployees(context *gin.Context) {
context.IndentedJSON(http.StatusOK, all_employee)
return
}
func main() {
router := gin.Default()
router.GET("/allemployees", getEmployees)
}这是卷曲输出
curl http://localhost:9099/allemployees {}
发布于 2022-08-03 11:29:15
发生这种情况是因为字段"id“未导出。
若要将json解编组到结构的字段,则需要导出该字段。
将模型更改为:
type employee struct {
Id int64 `json:"id" binding:"required"`
} 应该能解决问题。
OBS:id != Id
这篇文章有更多关于它的详细信息:JSON and dealing with unexported fields
https://stackoverflow.com/questions/73217380
复制相似问题