如何在 Golang 中响应所有字段包含带有标签 omitempty 的字段?

How to response all field include field with tag omitempty in Golang?

在我的网络服务中,我有一个模型:

// Comment struct
type Comment struct {
    Owner            UserObject      `json:"owner"`
    ID               int64           `json:"id"`
    Message          string          `json:"message"`
    Mentions         []MentionObject `json:"mentions,omitempty"`
    CreatedAt        int64           `json:"created_at,omitempty"`
    UpdatedAt        int64           `json:"updated_at,omitempty"`
    Status           int             `json:"status,omitempty"`
    CanEdit          bool            `json:"can_edit"`
    CanDelete        bool            `json:"can_delete"`
}


// UserObject struct
type UserObject struct {
    ID       int64  `json:"id"`
    Username string `json:"username"`
    FullName string `json:"full_name"`
    Avatar   string `json:"avatar"`
}

// MentionObject struct
type MentionObject struct {
    ID     int64 `json:"id"`
    Length int64 `json:"length"`
    Offset int64 `json:"offset"`
}

我已经使用 gin gonic 进行路由

routes.GET("/user", func(c *gin.Context) {
        c.JSON(200, Comment{})
    })

我需要 return 这个结构的所有字段,我知道它会响应 json:

{
  "owner": {
    "id": 0,
    "username": "",
    "full_name": "",
    "avatar": ""
  },
  "id": 0,
  "message": "",
  "can_report": false,
  "can_edit": false,
  "can_delete": false
}

我知道这是对的,但我仍然希望得到所有领域的回应。 怎么做?

如果你不想从标签中删除 omitempty 值,因为你需要它用于其他目的,你可以在 Go 1.8+ 上定义一个新的 type 与您要序列化的相同,但没有 omitempty 标记值,然后只需将值从旧类型转换为新类型即可。

Here's an example of the 1.8+ "tag ignoring" type conversion

你也可以定义一个新的类型只有那些在原始类型中被省略的字段然后在新类型中嵌入原始类型like so.