Answer the question
In order to leave comments, you need to log in
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"`
}
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)
})
{"count":1,"result":{"Id":3,"Username":"andrey","Displayname":"Andrey (admin)"}}
{"count":1,"result":{"id":3,"user_name":"andrey","display_name":"Andrey (admin)"}}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question