From 9f35e3ef0e90ef948f05aa9e13d763b5cbb27340 Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Wed, 13 Mar 2019 12:56:30 -0700 Subject: [PATCH] add function to marshal raw nodes to json fixes https://github.com/ipfs/go-ipfs/issues/6076 --- merkledag_test.go | 22 ++++++++++++++++++++++ raw.go | 6 ++++++ 2 files changed, 28 insertions(+) diff --git a/merkledag_test.go b/merkledag_test.go index d222ce8..bc87f3b 100644 --- a/merkledag_test.go +++ b/merkledag_test.go @@ -3,6 +3,7 @@ package merkledag_test import ( "bytes" "context" + "encoding/json" "errors" "fmt" "io" @@ -640,6 +641,27 @@ func TestCidRawDoesnNeedData(t *testing.T) { } } +func TestRawToJson(t *testing.T) { + rawData := []byte{1, 2, 3, 4} + nd := NewRawNode(rawData) + encoded, err := nd.MarshalJSON() + if err != nil { + t.Fatal(err) + } + var res interface{} + err = json.Unmarshal(encoded, &res) + if err != nil { + t.Fatal(err) + } + resBytes, ok := res.(string) + if !ok { + t.Fatal("expected to marshal to a string") + } + if string(rawData) != resBytes { + t.Fatal("failed to round-trip bytes") + } +} + func TestGetManyDuplicate(t *testing.T) { ctx := context.Background() diff --git a/raw.go b/raw.go index d0e456a..a0adb4a 100644 --- a/raw.go +++ b/raw.go @@ -1,6 +1,7 @@ package merkledag import ( + "encoding/json" "fmt" "github.com/ipfs/go-block-format" @@ -94,4 +95,9 @@ func (rn *RawNode) Stat() (*ipld.NodeStat, error) { }, nil } +// MarshalJSON is required for our "ipfs dag" commands. +func (rn *RawNode) MarshalJSON() ([]byte, error) { + return json.Marshal(string(rn.RawData())) +} + var _ ipld.Node = (*RawNode)(nil)