Avoid panicking when text formatting a malformed oneof.
diff --git a/proto/text.go b/proto/text.go
index 51202bd..dd69110 100644
--- a/proto/text.go
+++ b/proto/text.go
@@ -37,6 +37,7 @@
"bufio"
"bytes"
"encoding"
+ "errors"
"fmt"
"io"
"log"
@@ -336,6 +337,15 @@
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()
+ }
}
}
diff --git a/proto/text_test.go b/proto/text_test.go
index 7ff180d..3eabaca 100644
--- a/proto/text_test.go
+++ b/proto/text_test.go
@@ -221,6 +221,8 @@
{&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())