C
C
coder4web2016-12-20 11:42:49
go
coder4web, 2016-12-20 11:42:49

How to respect structure tags when emitting JSON in gin-gonic?

I'm learning Go, first I'm implementing an API based on the Gin package.
Everything is going well, but there are all sorts of little things that are not given right off the bat.
We have a structure:

type User struct {
  Id          int    `json: "id"`
  Username    string `json: "user_name"`
  Displayname string `json: "display_name"`
}

and an HTTP request handler of the form:
router.GET("/mentor/:id", func(c *gin.Context) {
    var (
      user   User
      result gin.H
    )
    id := c.Param("id")
    db, _ := c.MustGet("databaseConn").(*sql.DB)
    row := db.QueryRow("select user_id, username, displayname from engine4_users where mentor=1 AND user_id = ?;", id)
    err := row.Scan(&user.Id, &user.Username, &user.Displayname)
    if err != nil {
      result = gin.H{"result": nil, "count": 0}
    } else {
      result = gin.H{"result": user, "count": 1}
    }
    c.JSON(http.StatusOK, result)
  })

As a result, we get JSON:
{"count":1,"result":{"Id":3,"Username":"andrey","Displayname":"Andrey (admin)"}}

The question is how to make structure tags used and JSON generated based on them, that is, in lowercase letters:
{"count":1,"result":{"id":3,"user_name":"andrey","display_name":"Andrey (admin)"}}

For net/http this is implemented using json.Marshal, but for Gin I can't figure it out.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya, 2016-12-20
@kinozol

To do this, just remove the space in `json: "id"`. Should be `json:"id"`
Ps And for net/http your example wouldn't work either.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question