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 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计