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

Signed-off-by: Leonard Lyubich <leonard@nspcc.ru>
This commit is contained in:
Leonard Lyubich 2020-11-13 17:02:30 +03:00 committed by Alex Vanin
parent 7e3e9e1cba
commit 8f8e977a3e
4 changed files with 45 additions and 4 deletions

View file

@ -104,3 +104,23 @@ func (x *XHeader) UnmarshalJSON(data []byte) error {
return nil
}
func (r *RequestMetaHeader) MarshalJSON() ([]byte, error) {
return protojson.MarshalOptions{
EmitUnpopulated: true,
}.Marshal(
RequestMetaHeaderToGRPCMessage(r),
)
}
func (r *RequestMetaHeader) UnmarshalJSON(data []byte) error {
msg := new(session.RequestMetaHeader)
if err := protojson.Unmarshal(data, msg); err != nil {
return err
}
*r = *RequestMetaHeaderFromGRPCMessage(msg)
return nil
}

View file

@ -66,3 +66,15 @@ func TestXHeaderJSON(t *testing.T) {
require.Equal(t, x, x2)
}
func TestRequestMetaHeaderJSON(t *testing.T) {
r := generateRequestMetaHeader(1, "bearer", "session")
data, err := r.MarshalJSON()
require.NoError(t, err)
r2 := new(session.RequestMetaHeader)
require.NoError(t, r2.UnmarshalJSON(data))
require.Equal(t, r, r2)
}

View file

@ -528,6 +528,17 @@ func (r *RequestMetaHeader) StableSize() (size int) {
return size
}
func (r *RequestMetaHeader) Unmarshal(data []byte) error {
m := new(session.RequestMetaHeader)
if err := goproto.Unmarshal(data, m); err != nil {
return err
}
*r = *RequestMetaHeaderFromGRPCMessage(m)
return nil
}
func (r *RequestVerificationHeader) StableMarshal(buf []byte) ([]byte, error) {
if r == nil {
return []byte{}, nil

View file

@ -118,16 +118,14 @@ func TestRequestMetaHeader_StableMarshal(t *testing.T) {
metaHeaderOrigin := generateRequestMetaHeader(10, "Bearer One", "Session One")
metaHeaderFrom := generateRequestMetaHeader(20, "Bearer Two", "Session Two")
metaHeaderFrom.SetOrigin(metaHeaderOrigin)
transport := new(grpc.RequestMetaHeader)
t.Run("non empty", func(t *testing.T) {
wire, err := metaHeaderFrom.StableMarshal(nil)
require.NoError(t, err)
err = goproto.Unmarshal(wire, transport)
require.NoError(t, err)
metaHeaderTo := new(session.RequestMetaHeader)
require.NoError(t, metaHeaderTo.Unmarshal(wire))
metaHeaderTo := session.RequestMetaHeaderFromGRPCMessage(transport)
require.Equal(t, metaHeaderFrom, metaHeaderTo)
})
}