From 767b740039853f9ede23699a36843f0992a9e7a9 Mon Sep 17 00:00:00 2001 From: Kevin Atkinson Date: Wed, 26 Sep 2018 20:35:04 -0400 Subject: [PATCH] Use (Un)MarshalText instead of (Un)MarshalJSON for encoding. This is more to the point and will also allow the use of apicid.Hash as keys is JSON objects. --- apicid/apicid.go | 17 ++++++++------- apicid/apicid_test.go | 48 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 9 deletions(-) create mode 100644 apicid/apicid_test.go diff --git a/apicid/apicid.go b/apicid/apicid.go index 4ff6585..22c4ea7 100644 --- a/apicid/apicid.go +++ b/apicid/apicid.go @@ -1,8 +1,6 @@ package apicid import ( - "encoding/json" - cid "github.com/ipfs/go-cid" "github.com/ipfs/go-cidutil/cidenc" mbase "github.com/multiformats/go-multibase" @@ -12,12 +10,12 @@ import ( var JSONBase mbase.Encoder = mbase.MustNewEncoder(mbase.Base58BTC) // apicid.Hash is a type to respesnt a CID in the API which marshals -// as a hash +// as a string type Hash struct { - str string // always in CidJSONBase + str string } -// FromCid created an APICid from a Cid +// FromCid creates an APICid from a Cid func FromCid(c cid.Cid) Hash { return Hash{c.Encode(JSONBase)} } @@ -42,12 +40,13 @@ func (c Hash) Encode(enc cidenc.Interface) string { return str } -func (c *Hash) UnmarshalJSON(b []byte) error { - return json.Unmarshal(b, &c.str) +func (c *Hash) UnmarshalText(b []byte) error { + c.str = string(b) + return nil } -func (c Hash) MarshalJSON() ([]byte, error) { - return json.Marshal(c.str) +func (c Hash) MarshalText() ([]byte, error) { + return []byte(c.str), nil } // Cid is type to represent a normal CID in the API which marshals diff --git a/apicid/apicid_test.go b/apicid/apicid_test.go new file mode 100644 index 0000000..b967f88 --- /dev/null +++ b/apicid/apicid_test.go @@ -0,0 +1,48 @@ +package apicid + +import ( + "encoding/json" + "testing" + + cid "github.com/ipfs/go-cid" +) + +func TestJson(t *testing.T) { + cid, _ := cid.Decode("zb2rhak9iRgDiik36KQBRr2qiCJHdyBH7YxFmw7FTdM6zo31m") + hash := FromCid(cid) + data, err := json.Marshal(hash) + if err != nil { + t.Fatal(err) + } + if string(data) != `"zb2rhak9iRgDiik36KQBRr2qiCJHdyBH7YxFmw7FTdM6zo31m"` { + t.Fatalf("json string incorrect: %s\n", data) + } + var hash2 Hash + err = json.Unmarshal(data, &hash2) + if err != nil { + t.Fatal(err) + } + if hash != hash2 { + t.Fatal("round trip failed") + } +} + +func TestJsonMap(t *testing.T) { + cid1, _ := cid.Decode("zb2rhak9iRgDiik36KQBRr2qiCJHdyBH7YxFmw7FTdM6zo31m") + cid2, _ := cid.Decode("QmRJggJREPCt7waGQKMXymrXRvrvsSiiPjgFbLK9isuM8K") + hash1 := FromCid(cid1) + hash2 := FromCid(cid2) + m := map[Hash]string{hash1: "a value", hash2: "something else"} + data, err := json.Marshal(m) + if err != nil { + t.Fatal(err) + } + m2 := map[Hash]string{} + err = json.Unmarshal(data, &m2) + if err != nil { + t.Fatal(err) + } + if len(m2) != 2 || m[hash1] != m2[hash1] || m[hash2] != m2[hash2] { + t.Fatal("round trip failed") + } +}