diff --git a/v2/session/json.go b/v2/session/json.go index ec24b584..e8306a86 100644 --- a/v2/session/json.go +++ b/v2/session/json.go @@ -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 +} diff --git a/v2/session/json_test.go b/v2/session/json_test.go index eee4878c..0a2033b7 100644 --- a/v2/session/json_test.go +++ b/v2/session/json_test.go @@ -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) +} diff --git a/v2/session/marshal.go b/v2/session/marshal.go index 5b21964f..cd5b3a99 100644 --- a/v2/session/marshal.go +++ b/v2/session/marshal.go @@ -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 diff --git a/v2/session/marshal_test.go b/v2/session/marshal_test.go index 5d257a57..00439178 100644 --- a/v2/session/marshal_test.go +++ b/v2/session/marshal_test.go @@ -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) }) }