问题描述
我将附件存储在 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 中,我可以使用 virtual 属性将 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的marshal和unmarshal只接收数据[]byte作为参数。我不确定如何在 BSON 的编组和解组中启动 AWS 会话。
我更喜欢在从 mongodb 查询后修改 URL,但我想在 1 个地方进行
解决方法
mongo-go
和 mgo
驱动程序在将 Go 值转换为 BSON 值或从 BSON 值转换时检查并调用某些已实现的接口。在您的类型上实现 bson.Marshaler
和 bson.Unmarshaler
,您可以在保存之前/加载之后执行任何操作。
调用默认的 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
}
另见相关:How to ignore nulls while unmarshalling a MongoDB document?