User  Secret  adminUser 秘密 adminUser 

Hypothetical, I run an API and when a user makes a GET request on the user resource, I will return relevant fields as a JSON

type User struct {
  Id      bson.ObjectId `json:"id,omitempty" bson:"_id,omitempty"`
  Name    string        `json:"name,omitempty" bson:"name,omitempty"`
  Secret  string        `json:"-,omitempty" bson:"secret,omitempty"`
}
json:"-"
{
  "id":1,
  "Name": "John"
}
json:"-"

Now, I am openning an admin only route where I would like to return the secret field. However, that would mean duplicating the User struct.

My current solution looks like this:

type adminUser struct {      
  Id      bson.ObjectId `json:"id,omitempty" bson:"_id,omitempty"`
  Name    string        `json:"name,omitempty" bson:"name,omitempty"`
  Secret  string        `json:"secret,omitempty" bson:"secret,omitempty"`
}

Is there a way to embed User into adminUser? Kind of like inheritance:

type adminUser struct {      
  User
  Secret  string        `json:"secret,omitempty" bson:"secret,omitempty"`
}

The above currently does not work, as only the field secret will be returned in this case.

Note: In the actual code base, there are few dozens fields. As such, the cost of duplicating code is high.

The actual mongo query is below:

func getUser(w http.ResponseWriter, r *http.Request) {
  ....omitted code...

  var user adminUser
  err := common.GetDB(r).C("users").Find(
      bson.M{"_id": userId},
  ).One(&user)
  if err != nil {
      return
  }
  common.ServeJSON(w, &user)
}

You should take a look at the bson package's inline flag (that is documented under bson.Marshal). It should allow you to do something like this:

type adminUser struct {
    User `bson:",inline"`
    Secret string `json:"secret,omitempty" bson:"secret,omitempty"`
}
adminUserUsersecret
SecretUseradminUsersecretadminUser

这篇关于Golang + MongoDB嵌入类型(将结构嵌入另一个结构中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!