douaipi3965 2016-08-22 10:21
浏览 37
已采纳

在Go中覆盖struct标签

I have an entity in my project that is viewable by public and by admin. Not all fields should be accessible by public.

For example

type Foo struct {
    Id        bson.ObjectId `json:"id" bson:"_id"`
    DateAdded time.Time     `json:"date_added" bson:"date_added"`
    Bar       string `json:"bar" bson:"bar"`      
    AdminOnly string        `json:"admin_only" bson:"admin_only"`
}

AdminOnly field should be only visible to admins. For now, when requests comes from public, I call separate method that copies every needed field to new struct

type FooPublic struct {
    Id        bson.ObjectId `json:"id" bson:"_id"`
    DateAdded time.Time     `json:"date_added" bson:"date_added"`
    Bar       string `json:"bar" bson:"bar"`
}

func (f *Foo) Public() (res FooPublic) {
    res = FooPublic{
        Id: f.Id,
        DateAdded: f.DateAdded,
        Bar:f.Bar,
    }
    return
}

But if I need to add new field to my entity, I need to add it in 3 places. In struct itself, in PublicFoo and in Public method.
This seems to be agains DRY principle. What is correct, idiomatic solution here? Can I define FooPublic so it overrides tags of needed fields? Or probably there is at least good way to copy corresponding fields from one struct to another, so I don't need to do this manually in Public method?

  • 写回答

1条回答 默认 最新

  • dtl19910708 2016-08-22 10:30
    关注

    In general this repetition can be avoided by using embedding. Your Foo type should embed FooPublic:

    type FooPublic struct {
        Id        bson.ObjectId `json:"id" bson:"_id"`
        DateAdded time.Time     `json:"date_added" bson:"date_added"`
        Bar       string        `json:"bar" bson:"bar"`      
    }
    
    type Foo struct {
        FooPublic
        AdminOnly string `json:"admin_only" bson:"admin_only"`
    }
    
    func (f *Foo) Public() FooPublic {
        return f.FooPublic
    }
    

    But if someone is able to call the Foo.Public(), that someone already has the Foo or *Foo value (and so can access the exported AdminOnly field), so what's the point?

    A better solution would be to use an interface, and not expose the Foo struct.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?