Search code examples
jsongopostgo-echo

can't parse JSON from a post requests


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?


Solution

  • 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