douxie7738 2013-10-09 18:06 采纳率: 0%
浏览 82
已采纳

Golang + MongoDB嵌入式类型(在另一个结构中嵌入一个结构)

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

As you can see, the Secret field in User has json:"-". This implies that in most operation that I would not like to return. In this case, a response would be

{
  "id":1,
  "Name": "John"
}

The field secret will not be returned as json:"-" omits the field.

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)
}
  • 写回答

2条回答 默认 最新

  • dongyuans61046 2013-10-09 18:35
    关注

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

    However, now you'll notice that you get duplicate key errors when you try to read from the database with this structure, since both adminUser and User contain the key secret.

    In your case I would remove the Secret field from User and only have the one in adminUser. Then whenever you need to write to the secret field, make sure you use an adminUser.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000
  • ¥30 ppOCRLabel导出识别结果失败
  • ¥15 Centos7 / PETGEM
  • ¥15 csmar数据进行spss描述性统计分析
  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题