forked from TrueCloudLab/frostfs-api-go
[#172] v2/container: Add JSON converter for container
Signed-off-by: Alex Vanin <alexey@nspcc.ru>
This commit is contained in:
parent
cb188e63b7
commit
2e1096200e
2 changed files with 58 additions and 0 deletions
36
v2/container/json.go
Normal file
36
v2/container/json.go
Normal file
|
@ -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)
|
||||
}
|
22
v2/container/json_test.go
Normal file
22
v2/container/json_test.go
Normal file
|
@ -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)
|
||||
})
|
||||
}
|
Loading…
Reference in a new issue