From b681b28e337c9acde82e33f5b341567c333ecb92 Mon Sep 17 00:00:00 2001 From: Alex Vanin Date: Mon, 19 Oct 2020 21:27:38 +0300 Subject: [PATCH] [#172] v2/netmap: Add JSON converter for node info Signed-off-by: Alex Vanin --- v2/netmap/json.go | 36 ++++++++++++++++++++++++++++++++++++ v2/netmap/json_test.go | 22 ++++++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 v2/netmap/json.go create mode 100644 v2/netmap/json_test.go diff --git a/v2/netmap/json.go b/v2/netmap/json.go new file mode 100644 index 0000000..6b840ca --- /dev/null +++ b/v2/netmap/json.go @@ -0,0 +1,36 @@ +package netmap + +import ( + "github.com/golang/protobuf/jsonpb" + netmap "github.com/nspcc-dev/neofs-api-go/v2/netmap/grpc" +) + +func NodeInfoToJSON(n *NodeInfo) []byte { + if n == nil { + return nil + } + + msg := NodeInfoToGRPCMessage(n) + m := jsonpb.Marshaler{} + + s, err := m.MarshalToString(msg) + if err != nil { + return nil + } + + return []byte(s) +} + +func NodeInfoFromJSON(data []byte) *NodeInfo { + if len(data) == 0 { + return nil + } + + msg := new(netmap.NodeInfo) + + if err := jsonpb.UnmarshalString(string(data), msg); err != nil { + return nil + } + + return NodeInfoFromGRPCMessage(msg) +} diff --git a/v2/netmap/json_test.go b/v2/netmap/json_test.go new file mode 100644 index 0000000..2dae126 --- /dev/null +++ b/v2/netmap/json_test.go @@ -0,0 +1,22 @@ +package netmap_test + +import ( + "testing" + + "github.com/nspcc-dev/neofs-api-go/v2/netmap" + "github.com/stretchr/testify/require" +) + +func TestNodeInfoJSON(t *testing.T) { + exp := generateNodeInfo("public key", "/multi/addr", 2) + + t.Run("non empty", func(t *testing.T) { + data := netmap.NodeInfoToJSON(exp) + require.NotNil(t, data) + + got := netmap.NodeInfoFromJSON(data) + require.NotNil(t, got) + + require.Equal(t, exp, got) + }) +}