Skip to content

Commit

Permalink
Add new option for the decoder - to disallow unknown fields (#959)
Browse files Browse the repository at this point in the history
Fixes #448
  • Loading branch information
vsaveliev authored and johanbrandhorst committed Jun 21, 2019
1 parent 883b764 commit d6fec18
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
16 changes: 14 additions & 2 deletions runtime/marshal_jsonpb.go
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ func decodeJSONPb(d *json.Decoder, v interface{}) error {
if !ok {
return decodeNonProtoField(d, v)
}
unmarshaler := &jsonpb.Unmarshaler{AllowUnknownFields: true}
unmarshaler := &jsonpb.Unmarshaler{AllowUnknownFields: allowUnknownFields}
return unmarshaler.UnmarshalNext(d, p)
}

Expand All @@ -186,7 +186,7 @@ func decodeNonProtoField(d *json.Decoder, v interface{}) error {
rv.Set(reflect.New(rv.Type().Elem()))
}
if rv.Type().ConvertibleTo(typeProtoMessage) {
unmarshaler := &jsonpb.Unmarshaler{AllowUnknownFields: true}
unmarshaler := &jsonpb.Unmarshaler{AllowUnknownFields: allowUnknownFields}
return unmarshaler.UnmarshalNext(d, rv.Interface().(proto.Message))
}
rv = rv.Elem()
Expand Down Expand Up @@ -248,3 +248,15 @@ var typeProtoMessage = reflect.TypeOf((*proto.Message)(nil)).Elem()
func (j *JSONPb) Delimiter() []byte {
return []byte("\n")
}

// allowUnknownFields helps not to return an error when the destination
// is a struct and the input contains object keys which do not match any
// non-ignored, exported fields in the destination.
var allowUnknownFields = true

// DisallowUnknownFields enables option in decoder (unmarshaller) to
// return an error when it finds an unknown field. This function must be
// called before using the JSON marshaller.
func DisallowUnknownFields() {
allowUnknownFields = false
}
19 changes: 19 additions & 0 deletions runtime/marshal_jsonpb_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -468,6 +468,25 @@ func TestJSONPbDecoderFields(t *testing.T) {
}
}

func TestJSONPbDecoderUnknownField(t *testing.T) {
var (
m runtime.JSONPb
got examplepb.ABitOfEverything
)
data := `{
"uuid": "6EC2446F-7E89-4127-B3E6-5C05E6BECBA7",
"unknownField": "111"
}`

runtime.DisallowUnknownFields()

r := strings.NewReader(data)
dec := m.NewDecoder(r)
if err := dec.Decode(&got); err == nil {
t.Errorf("m.Unmarshal(&got) not failed; want `unknown field` error; data=%q", data)
}
}

var (
fieldFixtures = []struct {
data interface{}
Expand Down

0 comments on commit d6fec18

Please sign in to comment.