2017-05-25 71 views
0

在我的web服務,我有一個模型:如何在Golang中響應所有字段包含標記爲omitempty的字段?

// 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"` 
} 

我用杜松子酒gonic路由

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

我需要回到這個結構的各個領域,我知道,這將響應JSON :

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

我知道這是對的,但我仍然希望全部迴應。 如何做到這一點?

回答

3

如果您不希望從標記中刪除omitempty值,因爲您需要將其用於其他目的,則可以使用Go 1.8或更高版本定義與您想要的相同的新type以序列化但沒有omitempty標記值,然後將值從舊類型轉換爲新類型。

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

你也可以定義一個新的類型與那些在原來的省略,然後嵌入領域原來在新型like so

相關問題