duanjinchi1982 2018-09-30 09:17
浏览 97
已采纳

无法从发布请求中解析JSON

I built an echo microservice api, with two routings: post and get.

The get method works fine, but the get method can't parse the JSON, meaning the struct is empty after the Bind() func.

It must be a very stupid and tiny thing I am missing... any help?

// 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
}

When running a post request with postman (to make sure: post method, url is to the correct route, in the body> under raw> JSON format, I send the JSON as expected ) I receive back status 200 ok, but empty json, whereas I would expect to receive the email attribute.

Any idea why the Bind() didn't extract the fields correctly?

  • 写回答

1条回答 默认 最新

  • dongmuyan5638 2018-09-30 09:31
    关注

    You should export the fields of your credentials-struct by capitalizing each first letter, otherwise the json-package doesn't know what fields you have:

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

    for more information: JSON and dealing with unexported fields

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?