diff --git a/protoc-gen-openapiv2/internal/genopenapi/types.go b/protoc-gen-openapiv2/internal/genopenapi/types.go index 5840211e09e..8af16d5c1da 100644 --- a/protoc-gen-openapiv2/internal/genopenapi/types.go +++ b/protoc-gen-openapiv2/internal/genopenapi/types.go @@ -184,7 +184,22 @@ func (m *RawExample) UnmarshalJSON(data []byte) error { return (*json.RawMessage)(m).UnmarshalJSON(data) } +// MarshalYAML implements yaml.Marshaler interface. +// +// It converts RawExample to one of yaml-supported types and returns it. +// +// From yaml.Marshaler docs: The Marshaler interface may be implemented +// by types to customize their behavior when being marshaled into a YAML +// document. The returned value is marshaled in place of the original +// value implementing Marshaler. func (e RawExample) MarshalYAML() (interface{}, error) { + // From docs, json.Unmarshal will store one of next types to data: + // - bool, for JSON booleans; + // - float64, for JSON numbers; + // - string, for JSON strings; + // - []interface{}, for JSON arrays; + // - map[string]interface{}, for JSON objects; + // - nil for JSON null. var data interface{} if err := json.Unmarshal(e, &data); err != nil { return nil, err diff --git a/protoc-gen-openapiv2/internal/genopenapi/types_test.go b/protoc-gen-openapiv2/internal/genopenapi/types_test.go index 46f5d953278..c6488fb8a78 100644 --- a/protoc-gen-openapiv2/internal/genopenapi/types_test.go +++ b/protoc-gen-openapiv2/internal/genopenapi/types_test.go @@ -26,8 +26,10 @@ func TestRawExample(t *testing.T) { Exp: `"1"`, }, { In: RawExample(`{"hello":"worldr"}`), - Exp: "hello:\n" + - " worldr\n", + Exp: ` + hello: + worldr + `, }} sr := newSpaceReplacer() @@ -77,9 +79,11 @@ func TestOpenapiSchemaObjectProperties(t *testing.T) { t.Run("yaml", func(t *testing.T) { t.Parallel() - const exp = "example:\n" + - " test1: 1\n" + - " test2: 2\n" + const exp = ` + example: + test1: 1 + test2: 2 + ` sr := newSpaceReplacer()