[#168] session: Implement binary/JSON encoders/decoders on XHeader

Signed-off-by: Leonard Lyubich <leonard@nspcc.ru>
This commit is contained in:
Leonard Lyubich 2020-11-13 16:58:08 +03:00 committed by Alex Vanin
parent 85d4713348
commit 7e3e9e1cba
4 changed files with 45 additions and 4 deletions

View file

@ -84,3 +84,23 @@ func (t *SessionToken) UnmarshalJSON(data []byte) error {
return nil
}
func (x *XHeader) MarshalJSON() ([]byte, error) {
return protojson.MarshalOptions{
EmitUnpopulated: true,
}.Marshal(
XHeaderToGRPCMessage(x),
)
}
func (x *XHeader) UnmarshalJSON(data []byte) error {
msg := new(session.XHeader)
if err := protojson.Unmarshal(data, msg); err != nil {
return err
}
*x = *XHeaderFromGRPCMessage(msg)
return nil
}

View file

@ -54,3 +54,15 @@ func TestSessionTokenJSON(t *testing.T) {
require.Equal(t, tok, tok2)
}
func TestXHeaderJSON(t *testing.T) {
x := generateXHeader("key", "value")
data, err := x.MarshalJSON()
require.NoError(t, err)
x2 := new(session.XHeader)
require.NoError(t, x2.UnmarshalJSON(data))
require.Equal(t, x, x2)
}

View file

@ -177,6 +177,17 @@ func (x *XHeader) StableSize() (size int) {
return size
}
func (x *XHeader) Unmarshal(data []byte) error {
m := new(session.XHeader)
if err := goproto.Unmarshal(data, m); err != nil {
return err
}
*x = *XHeaderFromGRPCMessage(m)
return nil
}
func (l *TokenLifetime) StableMarshal(buf []byte) ([]byte, error) {
if l == nil {
return []byte{}, nil

View file

@ -46,16 +46,14 @@ func TestCreateResponseBody_StableMarshal(t *testing.T) {
func TestXHeader_StableMarshal(t *testing.T) {
xheaderFrom := generateXHeader("X-Header-Key", "X-Header-Value")
transport := new(grpc.XHeader)
t.Run("non empty", func(t *testing.T) {
wire, err := xheaderFrom.StableMarshal(nil)
require.NoError(t, err)
err = goproto.Unmarshal(wire, transport)
require.NoError(t, err)
xheaderTo := new(session.XHeader)
require.NoError(t, xheaderTo.Unmarshal(wire))
xheaderTo := session.XHeaderFromGRPCMessage(transport)
require.Equal(t, xheaderFrom, xheaderTo)
})
}