Skip to content

don't panic when trying to check for required fields #510

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

Merged
merged 3 commits into from
Feb 3, 2018
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
12 changes: 11 additions & 1 deletion jsonpb/jsonpb.go
Original file line number Diff line number Diff line change
Expand Up @@ -1134,6 +1134,12 @@ func checkRequiredFields(pb proto.Message) error {
for i := 0; i < v.NumField(); i++ {
field := v.Field(i)
sfield := v.Type().Field(i)

if sfield.PkgPath != "" {
// blank PkgPath means the field is exported; skip if not exported
continue
}

if strings.HasPrefix(sfield.Name, "XXX_") {
continue
}
Expand All @@ -1156,8 +1162,12 @@ func checkRequiredFields(pb proto.Message) error {
sfield = v.Type().Field(0)
}

protoTag := sfield.Tag.Get("protobuf")
if protoTag == "" {
continue
}
var prop proto.Properties
prop.Init(sfield.Type, sfield.Name, sfield.Tag.Get("protobuf"), &sfield)
prop.Init(sfield.Type, sfield.Name, protoTag, &sfield)

switch field.Kind() {
case reflect.Map:
Expand Down
17 changes: 17 additions & 0 deletions jsonpb/jsonpb_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -533,6 +533,19 @@ func TestMarshalAnyJSONPBMarshaler(t *testing.T) {
}
}

func TestMarshalWithCustomValidation(t *testing.T) {
msg := dynamicMessage{rawJson: `{ "foo": "bar", "baz": [0, 1, 2, 3] }`, dummy: &dynamicMessage{}}

js, err := new(Marshaler).MarshalToString(&msg)
if err != nil {
t.Errorf("an unexpected error occurred when marshalling to json: %v", err)
}
err = Unmarshal(strings.NewReader(js), &msg)
if err != nil {
t.Errorf("an unexpected error occurred when unmarshalling from json: %v", err)
}
}

// Test marshaling message containing unset required fields should produce error.
func TestMarshalUnsetRequiredFields(t *testing.T) {
msgExt := &pb.Real{}
Expand Down Expand Up @@ -1004,6 +1017,10 @@ func (s *stringField) UnmarshalJSONPB(jum *Unmarshaler, js []byte) error {
// It provides implementations of JSONPBMarshaler and JSONPBUnmarshaler for JSON support.
type dynamicMessage struct {
rawJson string `protobuf:"bytes,1,opt,name=rawJson"`

// an unexported nested message is present just to ensure that it
// won't result in a panic (see issue #509)
dummy *dynamicMessage `protobuf:"bytes,2,opt,name=dummy"`
}

func (m *dynamicMessage) Reset() {
Expand Down