Explorar o código

jsonpb: check for nil in Marshal and return error to avoid panic. (#469)

Herbie Ong %!s(int64=8) %!d(string=hai) anos
pai
achega
49f2ba7d08
Modificáronse 2 ficheiros con 12 adicións e 0 borrados
  1. 4 0
      jsonpb/jsonpb.go
  2. 8 0
      jsonpb/jsonpb_test.go

+ 4 - 0
jsonpb/jsonpb.go

@@ -118,6 +118,10 @@ type JSONPBUnmarshaler interface {
 
 // Marshal marshals a protocol buffer into JSON.
 func (m *Marshaler) Marshal(out io.Writer, pb proto.Message) error {
+	v := reflect.ValueOf(pb)
+	if pb == nil || (v.Kind() == reflect.Ptr && v.IsNil()) {
+		return errors.New("Marshal called with nil")
+	}
 	writer := &errWriter{writer: out}
 	return m.marshalObject(writer, pb, "", "")
 }

+ 8 - 0
jsonpb/jsonpb_test.go

@@ -462,6 +462,14 @@ func TestMarshaling(t *testing.T) {
 	}
 }
 
+func TestMarshalingNil(t *testing.T) {
+	var msg *pb.Simple
+	m := &Marshaler{}
+	if _, err := m.MarshalToString(msg); err == nil {
+		t.Errorf("mashaling nil returned no error")
+	}
+}
+
 func TestMarshalJSONPBMarshaler(t *testing.T) {
 	rawJson := `{ "foo": "bar", "baz": [0, 1, 2, 3] }`
 	msg := dynamicMessage{rawJson: rawJson}