gpt4 book ai didi

json - 无法从帖子请求中解析 JSON

转载 作者:数据小太阳 更新时间:2023-10-29 03:31:31 25 4
gpt4 key购买 nike

我构建了一个 echo 微服务 api,有两个路由:post 和 get。

get 方法工作正常,但 get 方法无法解析 JSON,这意味着在 Bind() 函数之后结构为空。

这一定是我错过的一件非常愚蠢和微小的事情......有什么帮助吗?

// main.go
//--------------------------------------------------------------------
func main() {
e := echo.New()

e.GET("/getmethod", func(c echo.Context) error { return c.JSON(200, "good")})
e.POST("/login", handlers.HandleLogin)

e.Start("localhost:8000")

}


// handlers/login.go
//--------------------------------------------------------------------
type credentials struct {
email string `json:"email"`
pass string `json:"pass"`
}

//--------------------------------------------------------------------
func HandleLogin(c echo.Context) error {
var creds credentials
err := c.Bind(&creds)

if err != nil {
return c.JSON(http.StatusBadRequest, err) // 400
}

return c.JSON(http.StatusOK, creds.email) // 200
}

当使用 postman 运行 post 请求时(确保:post 方法,url 是正确的路由,在 body> raw> JSON 格式下,我按预期发送 JSON)我收到返回状态 200 ok,但是空 json,而我希望收到电子邮件属性。

知道为什么 Bind() 没有正确提取字段吗?

最佳答案

您应该通过将每个首字母大写来导出凭证结构的字段,否则 json-package 不知道您有哪些字段:

type credentials struct {
Email string `json:"email"`
Pass string `json:"pass"`
}

了解更多信息:JSON and dealing with unexported fields

关于json - 无法从帖子请求中解析 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52576499/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com