Explorar o código

Avoid panicking when text formatting a malformed oneof.

David Symonds %!s(int64=10) %!d(string=hai) anos
pai
achega
a57d29119a
Modificáronse 2 ficheiros con 12 adicións e 0 borrados
  1. 10 0
      proto/text.go
  2. 2 0
      proto/text_test.go

+ 10 - 0
proto/text.go

@@ -37,6 +37,7 @@ import (
 	"bufio"
 	"bytes"
 	"encoding"
+	"errors"
 	"fmt"
 	"io"
 	"log"
@@ -336,6 +337,15 @@ func writeStruct(w *textWriter, sv reflect.Value) error {
 				props.Parse(tag) // Overwrite the outer props.
 				// Write the value in the oneof, not the oneof itself.
 				fv = inner.Field(0)
+
+				// Special case to cope with malformed messages gracefully:
+				// If the value in the oneof is a nil pointer, don't panic
+				// in writeAny.
+				if fv.Kind() == reflect.Ptr && fv.IsNil() {
+					// Use errors.New so writeAny won't render quotes.
+					msg := errors.New("/* nil */")
+					fv = reflect.ValueOf(&msg).Elem()
+				}
 			}
 		}
 

+ 2 - 0
proto/text_test.go

@@ -221,6 +221,8 @@ func TestTextOneof(t *testing.T) {
 		{&pb.Communique{Union: &pb.Communique_Msg{
 			&pb.Strings{StringField: proto.String("why hello!")},
 		}}, `msg:<string_field:"why hello!" >`},
+		// bad oneof (should not panic)
+		{&pb.Communique{Union: &pb.Communique_Msg{nil}}, `msg:/* nil */`},
 	}
 	for _, test := range tests {
 		got := strings.TrimSpace(test.m.String())