Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Discard unknown JSON fields by default #518

Merged
merged 2 commits into from
Jun 5, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion codec.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,9 @@ func (c *protoJSONCodec) Unmarshal(binary []byte, message any) error {
if len(binary) == 0 {
return errors.New("zero-length payload is not a valid JSON object")
}
var options protojson.UnmarshalOptions
// Discard unknown fields so clients and servers aren't forced to always use
// exactly the same version of the schema.
options := protojson.UnmarshalOptions{DiscardUnknown: true}
return options.Unmarshal(binary, protoMessage)
}

Expand Down
31 changes: 23 additions & 8 deletions codec_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,13 +100,28 @@ func TestStableCodec(t *testing.T) {
func TestJSONCodec(t *testing.T) {
t.Parallel()

var empty emptypb.Empty
codec := &protoJSONCodec{name: "json"}
err := codec.Unmarshal([]byte{}, &empty)
assert.NotNil(t, err)
assert.True(
t,
strings.Contains(err.Error(), "valid JSON"),
assert.Sprintf(`error message should explain that "" is not a valid JSON object`),
)

t.Run("success", func(t *testing.T) {
t.Parallel()
err := codec.Unmarshal([]byte("{}"), &emptypb.Empty{})
assert.Nil(t, err)
})

t.Run("unknown fields", func(t *testing.T) {
t.Parallel()
err := codec.Unmarshal([]byte(`{"foo": "bar"}`), &emptypb.Empty{})
assert.Nil(t, err)
})

t.Run("empty string", func(t *testing.T) {
t.Parallel()
err := codec.Unmarshal([]byte{}, &emptypb.Empty{})
assert.NotNil(t, err)
assert.True(
t,
strings.Contains(err.Error(), "valid JSON"),
assert.Sprintf(`error message should explain that "" is not a valid JSON object`),
)
})
}