我在向redis插入文档时遇到问题。
我在 Go 中有一个数据结构:
type ArticleCovers struct {
ID int
Covers ArticleCovers
ArticleTypeID int
Address Address `gorm:"ForeignKey:AddressID"`
}
我想将这样的数据添加到 Redis 中:
[ID:1 Cover:[http://chuabuuminh.vn/UserImages/2012/12/10/1/chinh_dien_jpg.jpg] ArticleTypeID:1 Address:map[Street: City:<nil> District:<nil> DistrictID:0 ID:0 Slug: Lat:0 Long:0 Ward:<nil> WardID:0 CityID:0]]
但是当我运行 Redis.HMSet("test", structs.Map(ret))
它返回错误:redis: can't marshal postgresql.ArticleCovers (consider implementing encoding .BinaryMarshaler)
.
谁能帮我解决我的问题,非常感谢你!
最佳答案
如错误消息所述,您需要实现 BinaryMarshaler
ArticleCovers
类型的界面:
type ArticleCovers struct {
ID int
Covers ArticleCovers
ArticleTypeID int
Address Address `gorm:"ForeignKey:AddressID"`
}
func (ac ArticleCovers) MarshalBinary() ([]byte, error) {
return []byte(fmt.Sprintf("%v-%v", ac.ID, ac.ArticleTypeID)), nil
}
请注意,这只会添加 ID
和 ArticleTypeID
字段。我不知道是什么
ArticleCovers
和 Address
类型看起来很像,但通常您想调用
相同的方法:
func (ac ArticleCovers) MarshalBinary() ([]byte, error) {
covers, err := ac.Covers.MarshalBinary()
if err != nil {
return nil, err
}
address, err := ac.Address.MarshalBinary()
if err != nil {
return nil, err
}
return []byte(fmt.Sprintf("%v-%v-%v-%v",
ac.ID, ac.ArticleTypeID, covers, address)
}
我不知道这种格式对您的数据是否有意义。你可能想使用 定义编码格式如json。
您可能还想实现 BinaryUnmarshaler
接口(interface)。
这样做留作练习 ;-)
关于arrays - 如何在Golang中将数组文档设置到redis中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44771474/