From 2e1096200ed8a42a8e33fa966209fd49d3eb8785 Mon Sep 17 00:00:00 2001 From: Alex Vanin Date: Mon, 19 Oct 2020 21:23:11 +0300 Subject: [PATCH] [#172] v2/container: Add JSON converter for container Signed-off-by: Alex Vanin --- v2/container/json.go | 36 ++++++++++++++++++++++++++++++++++++ v2/container/json_test.go | 22 ++++++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 v2/container/json.go create mode 100644 v2/container/json_test.go diff --git a/v2/container/json.go b/v2/container/json.go new file mode 100644 index 0000000..edd7d48 --- /dev/null +++ b/v2/container/json.go @@ -0,0 +1,36 @@ +package container + +import ( + "github.com/golang/protobuf/jsonpb" + container "github.com/nspcc-dev/neofs-api-go/v2/container/grpc" +) + +func ContainerToJSON(c *Container) []byte { + if c == nil { + return nil + } + + msg := ContainerToGRPCMessage(c) + m := jsonpb.Marshaler{} + + s, err := m.MarshalToString(msg) + if err != nil { + return nil + } + + return []byte(s) +} + +func ContainerFromJSON(data []byte) *Container { + if len(data) == 0 { + return nil + } + + msg := new(container.Container) + + if err := jsonpb.UnmarshalString(string(data), msg); err != nil { + return nil + } + + return ContainerFromGRPCMessage(msg) +} diff --git a/v2/container/json_test.go b/v2/container/json_test.go new file mode 100644 index 0000000..5a3f551 --- /dev/null +++ b/v2/container/json_test.go @@ -0,0 +1,22 @@ +package container_test + +import ( + "testing" + + "github.com/nspcc-dev/neofs-api-go/v2/container" + "github.com/stretchr/testify/require" +) + +func TestContainerJSON(t *testing.T) { + exp := generateContainer("container") + + t.Run("non empty", func(t *testing.T) { + data := container.ContainerToJSON(exp) + require.NotNil(t, data) + + got := container.ContainerFromJSON(data) + require.NotNil(t, got) + + require.Equal(t, exp, got) + }) +}