share formatter between request reader and reponse writer for -format-error

This commit is contained in:
Mikhail Katychev 2020-05-14 18:03:40 -05:00
parent f2808e4c71
commit 71db189b99
No known key found for this signature in database
GPG Key ID: 9E8549CD2CEB5E59
3 changed files with 12 additions and 24 deletions

View File

@ -656,7 +656,7 @@ func main() {
}
if h.Status.Code() != codes.OK {
if *formatError {
grpcurl.HandleFormatAndPrintStatus(grpcurl.Format(*format), os.Stderr, h.Status, *emitDefaults, includeSeparators)
grpcurl.PrintFormattedStatus(os.Stderr, h.Status, formatter)
} else {
grpcurl.PrintStatus(os.Stderr, h.Status, formatter)
}

View File

@ -429,24 +429,6 @@ func (h *DefaultEventHandler) OnReceiveTrailers(stat *status.Status, md metadata
}
}
// HandleFormatAndPrintStatus passes the writer, status object, and formatter (if applicable)
// to the appropriate status printing function
func HandleFormatAndPrintStatus(format Format, w io.Writer, stat *status.Status, emitJSONDefaultFields, includeTextSeparator bool) {
var formatter Formatter
switch format {
case FormatJSON:
formatter = NewJSONFormatter(
emitJSONDefaultFields,
anyResolverWithFallback{AnyResolver: jsonpb.Marshaler{Indent: " "}.AnyResolver})
case FormatText:
formatter = NewTextFormatter(includeTextSeparator)
default:
fmt.Errorf("unknown format: %s", format)
return
}
PrintFormattedStatus(w, stat, formatter)
}
// PrintStatus prints details about the given status to the given writer. The given
// formatter is used to print any detail messages that may be included in the status.
// If the given status has a code of OK, "OK" is printed and that is all. Otherwise,

View File

@ -176,26 +176,30 @@ func TestHandler(t *testing.T) {
}
func TestPrintFormattedStatus(t *testing.T) {
jsonFormatter := NewJSONFormatter(
true,
anyResolverWithFallback{AnyResolver: jsonpb.Marshaler{Indent: " "}.AnyResolver})
textFormatter := NewTextFormatter(true)
testCases := []struct {
input *status.Status
format Format
formatter Formatter
expectedOutput string
}{
{
input: status.New(codes.InvalidArgument, "Missing Argument"),
format: FormatJSON,
formatter: jsonFormatter,
expectedOutput: statusAsJSON,
},
{
input: status.New(codes.InvalidArgument, "Missing Argument"),
format: FormatText,
formatter: textFormatter,
expectedOutput: statusAsText,
},
}
for _, tc := range testCases {
var b bytes.Buffer
HandleFormatAndPrintStatus(tc.format, &b, tc.input, false, true)
PrintFormattedStatus(&b, tc.input, tc.formatter)
got := b.String()
if !compare(tc.expectedOutput, got) {
t.Errorf("Incorrect output. Expected:\n%s\nGot:\n%s", tc.expectedOutput, got)
@ -276,7 +280,9 @@ Response contents:
`
statusAsJSON = `{
"code": 3,
"message": "Missing Argument"
"message": "Missing Argument",
"details": [
]
}`
statusAsText = `code: 3
message: "Missing Argument"`