gpt4 book ai didi

go - 如何使用虚拟属性

转载 作者:行者123 更新时间:2023-12-03 10:09:12 26 4
gpt4 key购买 nike

我将附件作为附件对象存储在 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 session 检索。
在 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 的 marshal 和 unmarshal 只接收 data []byte 作为参数。我不确定如何在 BSON 的编码和解码中启动 AWS session 。
我更喜欢在从 mongodb 查询后修改 URL,但我想在 1 个地方进行

最佳答案

mongo-gomgo驱动程序在将 Go 值转换为 BSON 值/从 BSON 值转换时检查并调用某些已实现的接口(interface)。实现 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?

关于go - 如何使用虚拟属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65772480/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com