Skip to content

Commit b179dcc

Browse files
fredbiclaude
andcommitted
feat: response-level examples by mime on struct swagger:response
OpenAPI 2.0 lets a Response object carry an `examples` map keyed by mime type (`examples: {application/json: {…}}`). The `swagger:operation` YAML path already emitted this for free (raw YAML unmarshalled straight into spec.Response), but the struct-based `swagger:response` annotation path had no way to express it — no `examples` keyword existed. Add an `examples` grammar keyword (raw-block, CtxResponse-only) joined to the lexer's YAML-body set so the mime→object nesting survives. The responses builder's applyBlockToDecl now finds the `examples:` block in the response decl comment and parses its body via yaml.UnmarshalBody into Response.examples (map[string]any keyed by mime type). A malformed block raises a non-fatal diagnostic and is skipped. The singular schema `example:` decorator is untouched — OAS2 reserves the plural `examples` for the Response object. Out of scope (unchanged): per-request dynamic example values. Tested by the enhancements/response-examples-by-mime fixture + integration coverage (mime-keyed map with a JSON object and an XML string, body $ref and description preserved) with a golden. * contributes go-swagger/go-swagger#2871 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Signed-off-by: Frederic BIDON <fredbi@yahoo.com>
1 parent 637e2c4 commit b179dcc

7 files changed

Lines changed: 211 additions & 9 deletions

File tree

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
2+
// SPDX-License-Identifier: Apache-2.0
3+
4+
// Package response_examples_by_mime witnesses response-level `examples`
5+
// (a map keyed by mime type) on a struct-based `swagger:response`
6+
// (go-swagger#2871).
7+
//
8+
// OAS2 reserves the plural `examples` keyword for the Response object;
9+
// the value is a `{mimeType: example}` map. The `swagger:operation` YAML
10+
// path already carries this for free (it unmarshals straight into the
11+
// spec types — see fixtures/bugs/1713 and fixtures/bugs/2871); this
12+
// fixture exercises the Go-struct `swagger:response` path, where the
13+
// `examples:` block in the decl comment is parsed into Response.examples.
14+
package response_examples_by_mime
15+
16+
// Widget is the response payload.
17+
//
18+
// swagger:model Widget
19+
type Widget struct {
20+
Name string `json:"name"`
21+
}
22+
23+
// WidgetResponse returns a widget, with response-level examples per mime type.
24+
//
25+
// swagger:response widgetResponse
26+
//
27+
// examples:
28+
//
29+
// application/json:
30+
// name: alice
31+
// count: 3
32+
// application/xml: "<widget><name>alice</name></widget>"
33+
type WidgetResponse struct {
34+
// in: body
35+
Body Widget `json:"body"`
36+
}
37+
38+
// GetWidgets swagger:route GET /widgets widgets getWidgets
39+
//
40+
// Get a widget.
41+
//
42+
// Responses:
43+
//
44+
// 200: widgetResponse
45+
func GetWidgets() {}
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
{
2+
"swagger": "2.0",
3+
"paths": {
4+
"/widgets": {
5+
"get": {
6+
"tags": [
7+
"widgets"
8+
],
9+
"summary": "Get a widget.",
10+
"operationId": "getWidgets",
11+
"responses": {
12+
"200": {
13+
"$ref": "#/responses/widgetResponse"
14+
}
15+
}
16+
}
17+
}
18+
},
19+
"definitions": {
20+
"Widget": {
21+
"type": "object",
22+
"title": "Widget is the response payload.",
23+
"properties": {
24+
"name": {
25+
"type": "string",
26+
"x-go-name": "Name"
27+
}
28+
},
29+
"x-go-package": "github.com/go-openapi/codescan/fixtures/enhancements/response-examples-by-mime"
30+
}
31+
},
32+
"responses": {
33+
"widgetResponse": {
34+
"description": "WidgetResponse returns a widget, with response-level examples per mime type.",
35+
"schema": {
36+
"$ref": "#/definitions/Widget"
37+
},
38+
"examples": {
39+
"application/json": {
40+
"count": 3,
41+
"name": "alice"
42+
},
43+
"application/xml": "\u003cwidget\u003e\u003cname\u003ealice\u003c/name\u003e\u003c/widget\u003e"
44+
}
45+
}
46+
}
47+
}

‎internal/builders/responses/README.md‎

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -39,11 +39,22 @@ same. Divergences are called out below.
3939

4040
`Build(responses)` looks up the response by name (from
4141
`r.Decl.ResponseNames()`), runs `applyBlockToDecl` to capture the
42-
top-level description, then calls `buildFromType` on the declared
43-
type. `buildFromType` unwraps pointers, dispatches named types and
44-
aliases. Unlike parameters, **anonymous types are rejected**:
45-
`responses_test.go` documents the rationale — the top-level
46-
response-as-alias case under default mode is deferred to v2.
42+
top-level description **and the response-level `examples:` block**, then
43+
calls `buildFromType` on the declared type. `buildFromType` unwraps
44+
pointers, dispatches named types and aliases. Unlike parameters,
45+
**anonymous types are rejected**: `responses_test.go` documents the
46+
rationale — the top-level response-as-alias case under default mode is
47+
deferred to v2.
48+
49+
`examples:` is the OAS2 **response-scoped** keyword (plural): a YAML map
50+
keyed by mime type (`examples:` then an indented `application/json: {…}`)
51+
parsed into `Response.examples` (go-swagger#2871). It is the
52+
`CtxResponse`-only `examples` grammar keyword, joined to the lexer's
53+
YAML-body set so the mime→object nesting survives. The singular
54+
`example:` is a schema/param/header decorator, handled per-field /
55+
per-body, not here. The `swagger:operation` YAML path carries examples
56+
for free via the spec unmarshal; this is the struct-`swagger:response`
57+
counterpart.
4758

4859
For each non-embedded exported field, `processResponseField` runs:
4960

‎internal/builders/responses/walker.go‎

Lines changed: 42 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,12 @@
44
package responses
55

66
import (
7+
"encoding/json"
78
"go/ast"
89

910
"github.com/go-openapi/codescan/internal/builders/handlers"
11+
"github.com/go-openapi/codescan/internal/parsers/grammar"
12+
"github.com/go-openapi/codescan/internal/parsers/yaml"
1013
oaispec "github.com/go-openapi/spec"
1114
)
1215

@@ -64,12 +67,48 @@ func collectHeaderItemsLevels(expr ast.Expr, it *oaispec.Items, level int) []hea
6467

6568
// applyBlockToDecl parses the top-level response doc through grammar
6669
// and writes the description to resp.Description via the grammar
67-
// parser's prose accumulator. Does not dispatch any property
68-
// keywords — the v1 SectionedParser only accepted description at the
69-
// top level, no taggers.
70+
// parser's prose accumulator, plus the response-level `examples:`
71+
// block (the only keyword the response decl level accepts).
7072
func (r *Builder) applyBlockToDecl(resp *oaispec.Response) {
7173
block := r.ParseBlock(r.Decl.Comments)
7274
resp.Description = block.Prose()
75+
r.applyResponseExamples(block, resp)
76+
}
77+
78+
// applyResponseExamples parses a response-level `examples:` block — a YAML
79+
// map keyed by mime type (`examples:` then `application/json: {…}`) — onto
80+
// resp.Examples (the OAS2 Response.examples field). This is the plural,
81+
// response-scoped keyword (go-swagger#2871); the singular schema `example:`
82+
// is handled per-field / per-body elsewhere. The `swagger:operation` YAML
83+
// path already carries examples for free via the spec unmarshal — this
84+
// covers only the struct-based `swagger:response`.
85+
func (r *Builder) applyResponseExamples(block grammar.Block, resp *oaispec.Response) {
86+
var prop grammar.Property
87+
var found bool
88+
for p := range block.Properties() {
89+
if p.Keyword.Name == grammar.KwExamples {
90+
prop, found = p, true
91+
break
92+
}
93+
}
94+
if !found || prop.Body == "" {
95+
return
96+
}
97+
98+
examples := make(map[string]any)
99+
if err := yaml.UnmarshalBody(prop.Body, func(b []byte) error {
100+
return json.Unmarshal(b, &examples)
101+
}); err != nil {
102+
r.RecordDiagnostic(grammar.Warnf(
103+
prop.Pos, grammar.CodeInvalidAnnotation,
104+
"could not parse response examples block as a mime-keyed YAML map: %v", err,
105+
))
106+
return
107+
}
108+
109+
if len(examples) > 0 {
110+
resp.Examples = examples
111+
}
73112
}
74113

75114
// applyBlockToHeader parses afld.Doc through grammar and dispatches
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
2+
// SPDX-License-Identifier: Apache-2.0
3+
4+
package integration_test
5+
6+
import (
7+
"testing"
8+
9+
"github.com/go-openapi/codescan"
10+
"github.com/go-openapi/codescan/internal/scantest"
11+
"github.com/go-openapi/testify/v2/assert"
12+
"github.com/go-openapi/testify/v2/require"
13+
)
14+
15+
// TestCoverage_ResponseExamplesByMime covers response-level `examples` (a map
16+
// keyed by mime type) on a struct-based `swagger:response` (go-swagger#2871).
17+
//
18+
// The `swagger:operation` YAML path already carries examples for free (see
19+
// coverage_bug_1713 / coverage_bug_2871); this verifies the Go-struct
20+
// `swagger:response` path, where the `examples:` block in the decl comment is
21+
// parsed into the OAS2 Response.examples field.
22+
func TestCoverage_ResponseExamplesByMime(t *testing.T) {
23+
doc, err := codescan.Run(&codescan.Options{
24+
Packages: []string{"./enhancements/response-examples-by-mime/..."},
25+
WorkDir: scantest.FixturesDir(),
26+
ScanModels: true,
27+
})
28+
require.NoError(t, err)
29+
require.NotNil(t, doc)
30+
31+
resp, ok := doc.Responses["widgetResponse"]
32+
require.TrueT(t, ok, "expected a widgetResponse in the responses section")
33+
require.NotNil(t, resp.Examples, "response must carry an examples map")
34+
35+
jsonEx, ok := resp.Examples["application/json"].(map[string]any)
36+
require.TrueT(t, ok, "expected an application/json example object")
37+
assert.MapEqualT(t, map[string]any{"name": "alice", "count": float64(3)}, jsonEx)
38+
39+
xmlEx, ok := resp.Examples["application/xml"]
40+
require.TrueT(t, ok, "expected an application/xml example")
41+
assert.EqualT(t, any("<widget><name>alice</name></widget>"), xmlEx)
42+
43+
// The body schema and description survive alongside the examples.
44+
assert.EqualT(t, "WidgetResponse returns a widget, with response-level examples per mime type.", resp.Description)
45+
require.NotNil(t, resp.Schema)
46+
47+
scantest.CompareOrDumpJSON(t, doc, "enhancements_response_examples_by_mime.json")
48+
}

‎internal/parsers/grammar/keywords.go‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,7 @@ const (
180180
KwAdditionalProperties = "additionalProperties"
181181
KwDefault = "default"
182182
KwExample = "example"
183+
KwExamples = "examples"
183184
KwEnum = "enum"
184185
KwRequired = "required"
185186
KwReadOnly = "readOnly"
@@ -359,6 +360,16 @@ var keywords = []Keyword{
359360
ctx(CtxMeta)),
360361
keyword(KwResponses, asRawBlock(), ctx(CtxRoute, CtxOperation)),
361362
keyword(KwParameters, asRawBlock(), ctx(CtxRoute, CtxOperation)),
363+
// `examples:` is a YAML map keyed by mime type
364+
// (`examples:` then an indented `application/json: {…}`) populating
365+
// spec.Response.examples on a `swagger:response`. OAS2 reserves the
366+
// PLURAL `examples` for responses; the singular `example` above is
367+
// the schema / param / header / items decorator. Only the struct-
368+
// based `swagger:response` path needs this keyword — the
369+
// `swagger:operation` YAML path carries examples for free via the
370+
// spec unmarshal. The body is YAML-parsed downstream, so it joins the
371+
// yamlBody set in the lexer. See features/response-examples-by-mime.
372+
keyword(KwExamples, asRawBlock(), ctx(CtxResponse)),
362373
keyword(KwExtensions,
363374
asRawBlock(),
364375
ctx(CtxMeta, CtxRoute, CtxOperation, CtxSchema, CtxParam, CtxHeader)),

‎internal/parsers/grammar/lexer.go‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -708,7 +708,8 @@ func collectRawBlock(in []Token, i int, kw Keyword, out *[]Token) int {
708708
kw.Name == "infoExtensions" ||
709709
kw.Name == "securityDefinitions" ||
710710
kw.Name == KwTags ||
711-
kw.Name == KwSecurity
711+
kw.Name == KwSecurity ||
712+
kw.Name == KwExamples
712713
bodyLine := func(t Token) string {
713714
if yamlBody {
714715
return strings.TrimRightFunc(t.Raw, unicode.IsSpace)

0 commit comments

Comments
 (0)
⌂ 换网址