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 PointNet++的onnx模型只能使用一次
  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。