2017-06-27 3 views
0

文書を挿入する際に問題が発生しました。Golangで配列文書を赤字に設定する方法は?

私は行くのデータの構造体を持っている:私はRedisのには、このようなデータを追加したい

type ArticleCovers struct { 
    ID    int 
    Covers   ArticleCovers 
    ArticleTypeID int 
    Address  Address  `gorm:"ForeignKey:AddressID"` 
} 

[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)を。

私の問題を解決するのに役立つ人は誰ですか?これが唯一のIDArticleTypeIDフィールドを追加すること

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 
} 

注:エラーメッセージのよう

答えて

1

はあなたArticleCoversタイプのBinaryMarshalerインタフェースを実装する必要がある、と言います。私は ArticleCoversAddress種類はどのようなものか知らないが、多くの場合、あなたはその上 同じメソッドを呼び出したい:このフォーマットは、あなたのデータのために理にかなっている場合、私は知らない

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インターフェイスを実装することもできます。 はそれは

0

がCarpetsmokerが、これはそれを行う方法であるJSONエンコーディングについて言っていた通りの練習;-)として残してやって:

func (ac ArticleCovers) MarshalBinary() ([]byte, error) { 
    return json.Marshal(ac) 
} 

をデコードするときに使用したい場合はBinaryUnmarshaler

ますここで私の良い例をチェックアウトすることができますblog post

関連する問題