0

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?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Nyta
  • 557
  • 1
  • 7
  • 18
  • I don't much about Go, but does & really needed on `&creds` ? – Orel Eraki Sep 30 '18 at 09:22
  • Yes, this is because the bind function doesn't return the result, but parse it right onto the argument. Hence must be a pointer and not a copy – Nyta Sep 30 '18 at 09:24
  • You probably already seen it, but look on to this example, to see if you forgot something https://echo.labstack.com/guide/request – Orel Eraki Sep 30 '18 at 09:26
  • yup. checked. looks fine, but still doesn't work. thanks :/ @OrelEraki – Nyta Sep 30 '18 at 09:31
  • Possible duplicate of [JSON and dealing with unexported fields](https://stackoverflow.com/questions/11126793/json-and-dealing-with-unexported-fields) – Jonathan Hall Sep 30 '18 at 11:49

1 Answers1

4

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

sieberts
  • 528
  • 6
  • 15