如何使用虚拟属性

我将附件存储在mongodb中作为附件对象:


type Attachment struct {

  ID   string `bson:"_id" json:"id"`

  Name string `bson:"name" json:"name"`

  URL  string `bson:"url" json:"url"`

}

存储的 URL 是 PUT 请求的预签名 URL,使用 AWS 会话检索。在 Ruby on Rails 中,我可以使用虚拟属性将 URL 更改为 GET 请求的预签名 URL:


// models/attachment.rb

def url

  if super.present?

    // get the presigned URL for get request using the URL from super

  else

    super

  end

end

如何在 Go 中完成此操作?我在config.yaml中有我的配置,需要将yaml转换为struct。同时,BSON的封送和解只接收数据[]字节作为参数。我不确定如何在 BSON 的封送和取消元帅中启动 AWS 会话。


我更喜欢在从mongodb查询后修改URL,但我想在1个地方完成


守着一只汪
浏览 121回答 1
1回答

慕虎7371278

和 驱动程序在将 Go 值转换为 BSON 值时检查并调用某些已实现的接口。实现 bson。元帅和bson。在您的类型上取消marshaler,您可以在保存之前/加载后做任何事情。mongo-gomgo调用默认的 bson。Marhsal() 和 bson.Unmarshal() 函数执行常规的封送处理/取消封送过程,如果成功,则在返回之前执行所需的操作。例如:// Called when an Attachment is saved.func (a *Attachment) MarshalBSON() (data []byte, err error) {    data, err = bson.Marshal(a)    if err != nil {        return    }    // Do your additional thing here    return}// Called when an Attachment is loaded.func (a *Attachment) UnmarshalBSON(data []byte) error {    if err := bson.Unmarshal(data, &a); err != nil {        return err    }    // Do your additional thing here    return nil}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go