From a58512653fc313e6aa927585017c99f7563f93a3 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 15:40:16 +0000 Subject: [PATCH 1/2] feat: decode XML responses with encoding/xml An operation whose response is XML, text/xml, application/xml or +xml, with a schema and no JSON declared, was handed back as bytes, or not at all. It is now decoded with encoding/xml into the type its schema says and returned as a JSON body would be. The fields of every type an XML response holds get an xml tag beside their json one, as the schema's xml objects say: ,attr for an attribute, wrapper>item for a wrapped list, omitempty where the member is optional. The server writes such a body with encoding/xml, and the generated tests check a body that is no XML fails as a decoding error. Pins openapi to MarkRosemaker/openapi#34, for the xml object, and cassette to MarkRosemaker/cassette#10, which replays a body of text as the text it was. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019QCb1AfnATvpBQCH3PrX7Y --- README.md | 7 ++ README/features.md | 7 ++ go.mod | 4 +- go.sum | 8 +- ir/document.go | 2 + ir/ir.go | 6 +- ir/operation.go | 35 +++++- ir/xml.go | 117 +++++++++++++++++ render/imports.go | 1 + render/templates/client.gen.go.tmpl | 14 +++ render/templates/client.gen_test.go.tmpl | 19 ++- render/templates/server.gen.go.tmpl | 6 + testdata/golden/api/interactions.json | 26 ++++ testdata/golden/api/openapi.json | 51 ++++++++ testdata/golden/pkg/golden/api.js | 9 ++ testdata/golden/pkg/golden/client.gen.go | 53 ++++++++ testdata/golden/pkg/golden/client.gen_test.go | 119 ++++++++++++++++++ testdata/golden/pkg/golden/ir.json | 95 ++++++++++++++ testdata/golden/pkg/golden/server.gen.go | 62 +++++++++ testdata/golden/pkg/golden/types.gen.go | 17 +++ testdata/golden/pkg/golden/xml_test.go | 76 +++++++++++ .../MarkRosemaker/cassette/interaction.go | 43 +++++++ .../MarkRosemaker/cassette/large.go | 7 ++ .../MarkRosemaker/openapi/schema.go | 16 +++ .../github.com/MarkRosemaker/openapi/xml.go | 41 ++++++ vendor/modules.txt | 4 +- 26 files changed, 831 insertions(+), 14 deletions(-) create mode 100644 ir/xml.go create mode 100644 testdata/golden/pkg/golden/xml_test.go create mode 100644 vendor/github.com/MarkRosemaker/openapi/xml.go diff --git a/README.md b/README.md index 086ca403..226c75e7 100644 --- a/README.md +++ b/README.md @@ -245,6 +245,13 @@ How the specification maps onto Go: not JSON is returned as `[]byte`. The server copies a returned reader into the response, and the JavaScript client returns such a body as a `Blob`, or text as a string. +- **XML responses** — a `text/xml`, `application/xml` or `+xml` body with a + schema, where no JSON is declared, is decoded with `encoding/xml` into the + type its schema says, and returned as a JSON body would be. The fields of + every type it holds get an `xml` tag beside their `json` one, as the schema's + `xml` objects say: `,attr` for an attribute, `wrapper>item` for a wrapped + list, and `omitempty` where the member is optional. The server writes such a + body with `encoding/xml`. - **Paging** — an operation whose list is paged through by cursor also gets `XPages`, which yields each page, and `XAll`, which yields every item, each fetching the next page as the one before is used up, and stopping when the diff --git a/README/features.md b/README/features.md index c4b59416..6f051314 100644 --- a/README/features.md +++ b/README/features.md @@ -200,6 +200,13 @@ How the specification maps onto Go: not JSON is returned as `[]byte`. The server copies a returned reader into the response, and the JavaScript client returns such a body as a `Blob`, or text as a string. +- **XML responses** — a `text/xml`, `application/xml` or `+xml` body with a + schema, where no JSON is declared, is decoded with `encoding/xml` into the + type its schema says, and returned as a JSON body would be. The fields of + every type it holds get an `xml` tag beside their `json` one, as the schema's + `xml` objects say: `,attr` for an attribute, `wrapper>item` for a wrapped + list, and `omitempty` where the member is optional. The server writes such a + body with `encoding/xml`. - **Paging** — an operation whose list is paged through by cursor also gets `XPages`, which yields each page, and `XAll`, which yields every item, each fetching the next page as the one before is used up, and stopping when the diff --git a/go.mod b/go.mod index 712c4bb1..0fb2ec9b 100644 --- a/go.mod +++ b/go.mod @@ -3,9 +3,9 @@ module github.com/MarkRosemaker/openapi-codegen go 1.27 require ( - github.com/MarkRosemaker/cassette v0.0.0-20261127001959-2e9c977b04a7 + github.com/MarkRosemaker/cassette v0.0.0-20261127153817-bd6de8a6d78a github.com/MarkRosemaker/errpath v0.0.0-20261127001931-41afc0b86075 - github.com/MarkRosemaker/openapi v0.0.0-20261127002030-cbffd96bf394 + github.com/MarkRosemaker/openapi v0.0.0-20261127152632-cf3bbccfbf2b github.com/MarkRosemaker/openapi-compress v0.0.0-20261127050502-a5e936024b23 github.com/MarkRosemaker/openapi-edit v0.0.0-20261127002121-4ed97994dce4 github.com/MarkRosemaker/openapi-flatten v0.0.0-20261127002122-68a4af5d679f diff --git a/go.sum b/go.sum index 0b2f02ad..09c65b3c 100644 --- a/go.sum +++ b/go.sum @@ -1,15 +1,15 @@ cloud.google.com/go v0.123.0 h1:2NAUJwPR47q+E35uaJeYoNhuNEM9kM8SjgRgdeOJUSE= cloud.google.com/go v0.123.0/go.mod h1:xBoMV08QcqUGuPW65Qfm1o9Y4zKZBpGS+7bImXLTAZU= -github.com/MarkRosemaker/cassette v0.0.0-20261127001959-2e9c977b04a7 h1:s4iZamcKdjIP2Eh/PmRT4k3gKpQsyO88XwKhGorMeA8= -github.com/MarkRosemaker/cassette v0.0.0-20261127001959-2e9c977b04a7/go.mod h1:VC3Nc2r+4OJ1c6gRtJjs4H4jp0Iy11PbLPkys6+O/Y4= +github.com/MarkRosemaker/cassette v0.0.0-20261127153817-bd6de8a6d78a h1:tXWY98FzOSj7ZZlo4xYN5Xh2Nl3r2mOU22lbN2KAMfQ= +github.com/MarkRosemaker/cassette v0.0.0-20261127153817-bd6de8a6d78a/go.mod h1:VC3Nc2r+4OJ1c6gRtJjs4H4jp0Iy11PbLPkys6+O/Y4= github.com/MarkRosemaker/errpath v0.0.0-20261127001931-41afc0b86075 h1:qJS31SpFD4TSnn2cOfh7n3dhsyUleXsl0o+Svo4JzMk= github.com/MarkRosemaker/errpath v0.0.0-20261127001931-41afc0b86075/go.mod h1:VnXpUlsS3n1gSToedcQl2FCARGoA16CyitbCanUIv+I= github.com/MarkRosemaker/json2yaml v0.0.0-20261127001931-55b661ab603c h1:t+nWAPGKlpQTpcDVessJk4Jl1PABKdeO3bdEFisb1pY= github.com/MarkRosemaker/json2yaml v0.0.0-20261127001931-55b661ab603c/go.mod h1:eUwIjjooIESK1Ymw4bbMdSDF6feAblyZjxyoo5o/W6U= github.com/MarkRosemaker/jsonutil v0.0.0-20261127001933-b07dbcceebd6 h1:gLKnOUYT7pbfbTyE+uyZOtuK0HJXbE6K3ULP5Vr9hFk= github.com/MarkRosemaker/jsonutil v0.0.0-20261127001933-b07dbcceebd6/go.mod h1:SzjJlgYFlzpbFGvUUoQgfEsWlbai63bvhDPK8J0MNYM= -github.com/MarkRosemaker/openapi v0.0.0-20261127002030-cbffd96bf394 h1:8xQmeig75IYQq7xSgnY9tSQt64Zo97vRnDmO+6aNx4U= -github.com/MarkRosemaker/openapi v0.0.0-20261127002030-cbffd96bf394/go.mod h1:yrht5AwFPmZzg7PxpNesNN5EqdPEZ/aUw7DC6zIO75o= +github.com/MarkRosemaker/openapi v0.0.0-20261127152632-cf3bbccfbf2b h1:EwF9SivYmofrwTmxrwKe9Ctgsa8kYNSotwvzPA2X6IM= +github.com/MarkRosemaker/openapi v0.0.0-20261127152632-cf3bbccfbf2b/go.mod h1:yrht5AwFPmZzg7PxpNesNN5EqdPEZ/aUw7DC6zIO75o= github.com/MarkRosemaker/openapi-compare v0.0.0-20261127002121-d284f72800b7 h1:1EOen5YicLT0hb73OFD9BYfV4pkrFA/BKxOQNOVhaqo= github.com/MarkRosemaker/openapi-compare v0.0.0-20261127002121-d284f72800b7/go.mod h1:YKLfAnLhQ1OJ6/Qw9ECIx1ksyIwJ1hFEhcmfahGy/9E= github.com/MarkRosemaker/openapi-compress v0.0.0-20261127050502-a5e936024b23 h1:FDKq/Kcpgaghk25mWCx99D4r+jBzm+KcyTh2OXO3lAI= diff --git a/ir/document.go b/ir/document.go index 72c7ae0a..2ec65973 100644 --- a/ir/document.go +++ b/ir/document.go @@ -77,6 +77,8 @@ func FromDocument(doc *openapi.Document, packageName, userAgent string, producti return nil, fmt.Errorf("paths: %w", err) } + markXMLTags(doc, schemas) + if err := paginate(operations, schemas); err != nil { return nil, fmt.Errorf("paths: %w", err) } diff --git a/ir/ir.go b/ir/ir.go index 3349c0b8..d25ce97b 100644 --- a/ir/ir.go +++ b/ir/ir.go @@ -132,6 +132,8 @@ type Operation struct { // StreamSuccess is true when the operation's success response is not text (see Response.IsStream), so // SuccessReturn is io.ReadCloser and the method leaves the response body open for the caller. StreamSuccess bool `json:"streamSuccess,omitzero"` + // XMLSuccess is true when the operation's success response is XML (see Response.IsXML). + XMLSuccess bool `json:"xmlSuccess,omitzero"` // Pagination is how the operation's list is paged through by cursor, if it is: the client then has an iterator // of its pages and one of their items. Pagination *Pagination `json:"pagination,omitempty"` @@ -661,6 +663,8 @@ type Response struct { // IsStream is true for a success response whose media type is not text, such as a zip, a PDF or an image: GoType // is io.ReadCloser, the response body itself, which the caller reads and closes. IsStream bool `json:"isStream,omitzero"` + // IsXML is true when ContentType is XML and no JSON is declared: GoType is decoded with encoding/xml. + IsXML bool `json:"isXML,omitzero"` // BodyDescription is what the specification says beside the reference to the body's schema, of this response // alone, as a merged schema's description that differed from another's. BodyDescription string `json:"bodyDescription,omitzero"` @@ -680,7 +684,7 @@ func (op Operation) SuccessDescription() string { // IsJSON reports whether the response's media type is a JSON one, whose body the client decodes. func (r Response) IsJSON() bool { - return r.ContentType != "" && !r.IsRawBytes && !r.IsStream + return r.ContentType != "" && !r.IsRawBytes && !r.IsStream && !r.IsXML } // ReqBody is the IR representation of an operation request body. diff --git a/ir/operation.go b/ir/operation.go index 5c301e26..541bbf0d 100644 --- a/ir/operation.go +++ b/ir/operation.go @@ -102,7 +102,7 @@ func FromOperation( } } - responses, successReturn, rawBytesSuccess, streamSuccess, emptySuccess, err := fromResponses(op.Responses) + responses, successReturn, rawBytesSuccess, streamSuccess, xmlSuccess, emptySuccess, err := fromResponses(op.Responses) if err != nil { return nil, fmt.Errorf("responses: %w", err) } @@ -131,6 +131,7 @@ func FromOperation( Deprecated: op.Deprecated, RawBytesSuccess: rawBytesSuccess, StreamSuccess: streamSuccess, + XMLSuccess: xmlSuccess, EmptySuccess: emptySuccess, pagination: pagination, }, nil @@ -739,12 +740,13 @@ func fromRequestBody(rb *openapi.RequestBody) (*ReqBody, error) { return nil, nil } -func fromResponses(responses openapi.OperationResponses) (Responses, *GoType, bool, bool, bool, error) { +func fromResponses(responses openapi.OperationResponses) (Responses, *GoType, bool, bool, bool, bool, error) { var ( result Responses successReturn *GoType rawBytesSuccess bool streamSuccess bool + xmlSuccess bool emptySuccess bool ) @@ -760,6 +762,8 @@ func fromResponses(responses openapi.OperationResponses) (Responses, *GoType, bo var ( jsonContentType string jsonSchema *openapi.Schema + xmlContentType string + xmlSchema *openapi.Schema firstContentType string ) for mr, mt := range r.Content.ByIndex() { @@ -767,6 +771,10 @@ func fromResponses(responses openapi.OperationResponses) (Responses, *GoType, bo firstContentType = string(mr) } + if xmlContentType == "" && isXMLMediaType(string(mr)) && mt.Schema != nil { + xmlContentType, xmlSchema = string(mr), mt.Schema + } + if strings.Contains(string(mr), "json") { jsonContentType = string(mr) jsonSchema = mt.Schema @@ -779,6 +787,7 @@ func fromResponses(responses openapi.OperationResponses) (Responses, *GoType, bo contentType string isRawBytes bool isStream bool + isXML bool ) switch { @@ -790,9 +799,20 @@ func fromResponses(responses openapi.OperationResponses) (Responses, *GoType, bo goType, err = SchemaGoType(jsonSchema) if err != nil { - return nil, nil, false, false, false, fmt.Errorf("response %s: %w", code, err) + return nil, nil, false, false, false, false, fmt.Errorf("response %s: %w", code, err) } } + case xmlContentType != "": + // a body decoded with encoding/xml into the type its schema says + var err error + + goType, err = SchemaGoType(xmlSchema) + if err != nil { + return nil, nil, false, false, false, false, fmt.Errorf("response %s: %w", code, err) + } + + contentType, isXML = xmlContentType, true + jsonSchema = xmlSchema // the body's schema, whatever its encoding case firstContentType != "" && isSuccess && !cassette.IsText(firstContentType): // a zip, a PDF, an image or the like: the body itself, read as it arrives rather than all at once contentType = firstContentType @@ -818,6 +838,7 @@ func fromResponses(responses openapi.OperationResponses) (Responses, *GoType, bo IsSuccess: isSuccess, IsRawBytes: isRawBytes, IsStream: isStream, + IsXML: isXML, BodyDescription: refDescription(jsonSchema), }) @@ -830,11 +851,12 @@ func fromResponses(responses openapi.OperationResponses) (Responses, *GoType, bo successReturn = goType rawBytesSuccess = isRawBytes streamSuccess = isStream + xmlSuccess = isXML } } } - return result, successReturn, rawBytesSuccess, streamSuccess, emptySuccess, nil + return result, successReturn, rawBytesSuccess, streamSuccess, xmlSuccess, emptySuccess, nil } func isRange(code openapi.StatusCode) bool { @@ -929,3 +951,8 @@ func refDescription(s *openapi.Schema) string { return s.Description } + +// isXMLMediaType reports whether mediaType is XML: text/xml, application/xml or one ending in +xml. +func isXMLMediaType(mediaType string) bool { + return mediaType == "text/xml" || mediaType == "application/xml" || strings.HasSuffix(mediaType, "+xml") +} diff --git a/ir/xml.go b/ir/xml.go new file mode 100644 index 00000000..9a229e47 --- /dev/null +++ b/ir/xml.go @@ -0,0 +1,117 @@ +package ir + +import ( + "fmt" + "strings" + + "github.com/MarkRosemaker/openapi" +) + +// markXMLTags gives the fields of every schema an XML response holds, there or deeper, the xml tag that reads them as +// the schema's xml objects say: by their element's or attribute's name, a wrapped list through its wrapper. +func markXMLTags(doc *openapi.Document, schemas []Schema) { + inXML := map[string]bool{} + + var visit func(s *openapi.Schema) + + visit = func(s *openapi.Schema) { + if s == nil { + return + } + + if s.Ref != nil { + name, ok := strings.CutPrefix(s.Ref.Identifier, "#/components/schemas/") + if !ok || inXML[name] { + return + } + + inXML[name] = true + } + + v := deref(s) + for _, p := range v.Properties.ByIndex() { + visit(p) + } + + visit(v.Items) + + for _, l := range []openapi.SchemaList{v.AllOf, v.OneOf, v.AnyOf} { + for _, alt := range l { + visit(alt) + } + } + } + + for _, path := range doc.Paths.ByIndex() { + for _, op := range path.Operations { + for _, r := range op.Responses.ByIndex() { + for mr, mt := range r.Value.Content.ByIndex() { + if isXMLMediaType(string(mr)) { + visit(mt.Schema) + } + } + } + } + } + + for i := range schemas { + s := &schemas[i] + if !inXML[s.Name] { + continue + } + + comp := doc.Components.Schemas[s.Name] + if comp == nil { + continue + } + + for j := range s.Fields { + f := &s.Fields[j] + if prop := comp.Properties[f.JSONName]; prop != nil { + f.JSONTag += " " + xmlTag(f.JSONName, prop, f.Required) + } + } + } +} + +// xmlTag is the xml struct tag of the property name holding prop: an attribute, an element, or a wrapped list's items +// inside their wrapper. An optional one is left out when it holds nothing. +func xmlTag(name string, prop *openapi.Schema, required bool) string { + v := deref(prop) + + x := prop.XML + if x == nil { + x = v.XML + } + + elem := name + if x != nil && x.Name != "" { + elem = x.Name + } + + opt := "" + if !required { + opt = ",omitempty" + } + + switch { + case x != nil && x.Attribute: + return fmt.Sprintf(`xml:"%s,attr%s"`, elem, opt) + case v.Type == openapi.TypeArray && v.Items != nil: + item := elem + if ix := deref(v.Items).XML; ix != nil && ix.Name != "" { + item = ix.Name + } else if v.Items.XML != nil && v.Items.XML.Name != "" { + item = v.Items.XML.Name + } + + if x != nil && x.Wrapped { + return fmt.Sprintf(`xml:"%s>%s%s"`, elem, item, opt) + } + + // the items stand side by side, each an element of the items' name + return fmt.Sprintf(`xml:"%s%s"`, item, opt) + default: + return fmt.Sprintf(`xml:"%s%s"`, elem, opt) + } +} diff --git a/render/imports.go b/render/imports.go index 45023454..5f837142 100644 --- a/render/imports.go +++ b/render/imports.go @@ -38,6 +38,7 @@ var importPaths = map[string]string{ "time": "time", "url": "net/url", "uuid": "uuid", + "xml": "encoding/xml", "api": "github.com/go-api-libs/api", "apitest": "github.com/go-api-libs/api/apitest", diff --git a/render/templates/client.gen.go.tmpl b/render/templates/client.gen.go.tmpl index 1efe28bd..7e4da946 100644 --- a/render/templates/client.gen.go.tmpl +++ b/render/templates/client.gen.go.tmpl @@ -437,6 +437,20 @@ func (c *Client) {{.Name}}(ctx context.Context{{range .PathParams}}, {{.GoName}} } {{ end }}{{ end -}} + {{ if and .IsSuccess $op.SuccessReturn -}} + return {{ if not $op.SuccessReturn.NilByItself }}&{{ end }}out, nil + {{ else if .IsSuccess -}} + return nil + {{ else -}} + return {{if $op.SuccessReturn}}nil, {{end}}api.NewErrCustom(rsp, &out) + {{ end -}} + {{- else if .IsXML }} + {{- $out := .GoType }}{{ if and .IsSuccess $op.SuccessReturn }}{{ $out = $op.SuccessReturn }}{{ end }} + var out {{ $out }} + if err := xml.NewDecoder(rsp.Body).Decode(&out); err != nil { + return {{if $op.SuccessReturn}}nil, {{end}}{{ if $.Debug }}c.failed(ia, api.WrapDecodingError(rsp, err)){{ else }}api.WrapDecodingError(rsp, err){{ end }} + } + {{ if and .IsSuccess $op.SuccessReturn -}} return {{ if not $op.SuccessReturn.NilByItself }}&{{ end }}out, nil {{ else if .IsSuccess -}} diff --git a/render/templates/client.gen_test.go.tmpl b/render/templates/client.gen_test.go.tmpl index 83247833..a156ad91 100644 --- a/render/templates/client.gen_test.go.tmpl +++ b/render/templates/client.gen_test.go.tmpl @@ -122,6 +122,23 @@ func TestClient_Error(t *testing.T) { t.Fatalf("got: %T, want: *jsontext.SyntacticError", decErr.Err) } }) + {{- else if (index .Responses 0).IsXML }} + t.Run("decoding error", func(t *testing.T) { + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, {{ (index .Responses 0).GoConstant }}, {{ printf "%q" (index .Responses 0).ContentType }}, []byte("")))) + if err != nil { + t.Fatal(err) + } + + if _, err := c.{{.Name}}(t.Context(){{range .PathParams}}, {{ .ZeroVal }}{{end}} + {{- with .NilParamsExpr}}, {{ . }}{{ end -}} + {{if .RequestBody}}, {{if .RequestBody.Required}}{{$.MinimalLiteral .RequestBody.TypeName}}{{else}}nil{{end}}{{end}}); err == nil { + t.Fatal("expected error") + } else if decErr, ok := errors.AsType[*api.DecodingError](err); !ok { + t.Fatalf("got: %T, want: *api.DecodingError", err) + } else if _, ok := errors.AsType[*xml.SyntaxError](decErr.Err); !ok { + t.Fatalf("got: %T, want: *xml.SyntaxError", decErr.Err) + } + }) {{- end }}{{ end }} {{- $op := . }} {{- if and .RequestBody (not .RequestBody.Required) }} @@ -475,7 +492,7 @@ func TestClient_Interactions(t *testing.T) { } {{range .InteractionCalls}} {{- if .Op.SuccessReturn}} - {{- $check := and .IsSuccess (not .Op.RawBytesSuccess) (not .Op.StreamSuccess) }} + {{- $check := and .IsSuccess (not .Op.RawBytesSuccess) (not .Op.StreamSuccess) (not .Op.XMLSuccess) }} if {{ if $check }}out{{ else }}_{{ end }}, err := c.{{.Op.Name}}({{ if and .Op.Auth .Op.AuthOptional }}apitest.OptionalAuth(ctx){{ else }}ctx{{ end }}{{range .PathArgs}}, {{.}}{{end}}{{if .Op.ParamsInStruct}}, {{ if not .Op.ParamsInStruct.Required }}&{{ end }}{{.Op.ParamStructName}}{ {{range .QueryArgs}}{{.FieldName}}: {{.Literal}}, {{ end -}} diff --git a/render/templates/server.gen.go.tmpl b/render/templates/server.gen.go.tmpl index 077f82f1..3f822930 100644 --- a/render/templates/server.gen.go.tmpl +++ b/render/templates/server.gen.go.tmpl @@ -93,6 +93,12 @@ func RegisterService(svc Service, mux *http.ServeMux, pathPrefix string) { l.ErrorContext(ctx, "write error", slog.String("error", err.Error())) return } +{{- else if .XMLSuccess }} + if err := xml.NewEncoder(w).Encode(res); err != nil { + l.ErrorContext(ctx, "marshal error", slog.String("error", err.Error())) + http.Error(w, "Internal Server Error", http.StatusInternalServerError) + return + } {{- else if .SuccessReturn }} if err := json.MarshalWrite(w, res, {{ if $.HasWriteOnly }}jsonOptsResponse{{ else }}jsonOpts{{ end }}); err != nil { l.ErrorContext(ctx, "marshal error", slog.String("error", err.Error())) diff --git a/testdata/golden/api/interactions.json b/testdata/golden/api/interactions.json index 66b622c4..4c034cec 100644 --- a/testdata/golden/api/interactions.json +++ b/testdata/golden/api/interactions.json @@ -244,5 +244,31 @@ "response": { "statusCode": 204 } + }, + { + "request": { + "method": "GET", + "url": "https://api.example.com/v1/statements?q=1" + }, + "response": { + "statusCode": 200, + "header": { + "Content-Type": "text/xml;charset=UTF-8" + }, + "body": "\nSuccess\n0877097094\nhttps://example.com/GetStatement\nfirst\nsecond\nab\n" + } + }, + { + "request": { + "method": "GET", + "url": "https://api.example.com/v1/statements?q=2" + }, + "response": { + "statusCode": 200, + "header": { + "Content-Type": "text/xml;charset=UTF-8" + }, + "body": "\nFail\n1019\nStatement generation in progress. Please try again shortly.\n" + } } ] diff --git a/testdata/golden/api/openapi.json b/testdata/golden/api/openapi.json index b0601e31..36c8ccbf 100644 --- a/testdata/golden/api/openapi.json +++ b/testdata/golden/api/openapi.json @@ -11,6 +11,29 @@ } ], "paths": { + "/statements": { + "get": { + "operationId": "GetStatement", + "description": "An XML response is decoded with encoding/xml into the type its schema says: the root element, an attribute, child elements, a list whose items stand side by side, a wrapped list, and the elements only an error answer holds, which may be left out.", + "parameters": [ + { + "name": "q", + "in": "query", + "schema": { "type": "string" } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "text/xml": { + "schema": { "$ref": "#/components/schemas/FlexStatementResponse" } + } + } + } + } + } + }, "/pages/{id}": { "get": { "operationId": "getPage", @@ -1138,6 +1161,34 @@ }, "components": { "schemas": { + "FlexStatementResponse": { + "type": "object", + "properties": { + "timestamp": { + "type": "string", + "xml": { "attribute": true } + }, + "Status": { "type": "string" }, + "ReferenceCode": { "type": "string" }, + "Url": { "type": "string" }, + "Note": { + "type": "array", + "items": { "type": "string" } + }, + "Books": { + "type": "array", + "items": { + "type": "string", + "xml": { "name": "Book" } + }, + "xml": { "wrapped": true } + }, + "ErrorCode": { "type": "string" }, + "ErrorMessage": { "type": "string" } + }, + "required": ["timestamp", "Status"], + "xml": { "name": "FlexStatementResponse" } + }, "Problem": { "description": "A failure the server describes.", "type": "object", diff --git a/testdata/golden/pkg/golden/api.js b/testdata/golden/pkg/golden/api.js index 1427da3e..6ef4115c 100644 --- a/testdata/golden/pkg/golden/api.js +++ b/testdata/golden/pkg/golden/api.js @@ -9,6 +9,7 @@ * * Usage: * import './api.js'; // or + * const result = await window.API.getStatement(); * const result = await window.API.getPage(id); * const result = await window.API.search(); * const result = await window.API.getTrial(id); @@ -112,6 +113,14 @@ const join = (parts, sep, escape) => parts.map((p) => escape(p).replaceAll(sep, // ====================== PUBLIC API ====================== window.API = { + // GET /statements + getStatement: (params = {}) => { + const q = new URLSearchParams(); + if (params.q != null) q.set("q", String(params.q)); + return apiFetch(`/statements?${q}`, { + operationId: "GetStatement", + }); + }, // GET /pages/{id} // Retrieve a page getPage: (id) => apiFetch(`/pages/${id}`, { diff --git a/testdata/golden/pkg/golden/client.gen.go b/testdata/golden/pkg/golden/client.gen.go index 00a27c48..9def919e 100644 --- a/testdata/golden/pkg/golden/client.gen.go +++ b/testdata/golden/pkg/golden/client.gen.go @@ -7,6 +7,7 @@ package golden import ( "context" "encoding/json/v2" + "encoding/xml" "fmt" "io" "iter" @@ -79,6 +80,58 @@ func NewClient(opts ...ClientOption) (*Client, error) { return c, nil } +// An XML response is decoded with encoding/xml into the type its schema says: the root element, an attribute, child elements, a list whose items stand side by side, a wrapped list, and the elements only an error answer holds, which may be left out. +// +// GET /statements +func (c *Client) GetStatement(ctx context.Context, params *GetStatementParams) (*FlexStatementResponse, error) { + u := c.baseURL.JoinPath("statements") + if params != nil { + q := make(url.Values, 1) + + if params.Q != "" { + q["q"] = []string{params.Q} + } + + u.RawQuery = q.Encode() + } + + req := (&http.Request{ + Header: http.Header{ + "User-Agent": []string{c.userAgent}, + }, + Host: u.Host, + Method: http.MethodGet, + Proto: "HTTP/1.1", + ProtoMajor: 1, + ProtoMinor: 1, + URL: u, + }).WithContext(ctx) + + rsp, err := c.cli.Do(req) + if err != nil { + return nil, err + } + defer rsp.Body.Close() + + switch rsp.StatusCode { + case http.StatusOK: + // OK + switch mt, _, _ := strings.Cut(rsp.Header.Get("Content-Type"), ";"); mt { + case "text/xml": + var out FlexStatementResponse + if err := xml.NewDecoder(rsp.Body).Decode(&out); err != nil { + return nil, api.WrapDecodingError(rsp, err) + } + + return &out, nil + default: + return nil, api.NewErrUnknownContentType(rsp) + } + default: + return nil, api.NewErrUnknownStatusCode(rsp) + } +} + // Retrieve a page // // GET /pages/{id} diff --git a/testdata/golden/pkg/golden/client.gen_test.go b/testdata/golden/pkg/golden/client.gen_test.go index ce5b0d83..b3c8fcda 100644 --- a/testdata/golden/pkg/golden/client.gen_test.go +++ b/testdata/golden/pkg/golden/client.gen_test.go @@ -7,6 +7,7 @@ package golden import ( "encoding/json/jsontext" "encoding/json/v2" + "encoding/xml" "errors" "io" "net" @@ -23,6 +24,86 @@ import ( ) func TestClient_Error(t *testing.T) { + t.Run("GetStatement", func(t *testing.T) { + t.Run("transport error", func(t *testing.T) { + c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( + func(*http.Request) (*http.Response, error) { return nil, io.EOF }, + )})) + if err != nil { + t.Fatal(err) + } + + if _, err := c.GetStatement(t.Context(), nil); err == nil { + t.Fatal("expected error") + } else if !errors.Is(err, io.EOF) { + t.Fatalf("want: %v, got: %v", io.EOF, err) + } + }) + + t.Run("unknown status code", func(t *testing.T) { + srv := apitest.NewServer(t, http.StatusTeapot) + + baseURL, err := url.Parse(srv.URL) + if err != nil { + t.Fatal(err) + } + + c, err := NewClient(WithBaseURL(baseURL)) + if err != nil { + t.Fatal(err) + } + + if _, err := c.GetStatement(t.Context(), nil); err == nil { + t.Fatal("expected error") + } else if apiErr, ok := errors.AsType[*api.Error](err); !ok { + t.Fatalf("got: %T, want: *api.Error", err) + } else if apiErr.Err != api.ErrUnknownStatusCode { + t.Fatalf("got: %v, want: %v", apiErr.Err, api.ErrUnknownStatusCode) + } else if apiErr.Response.StatusCode != http.StatusTeapot { + t.Fatalf("got: %v, want: %v", apiErr.Response.StatusCode, http.StatusTeapot) + } + }) + + t.Run("unknown content type", func(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "foo") + w.WriteHeader(http.StatusOK) + })) + t.Cleanup(srv.Close) + + baseURL, err := url.Parse(srv.URL) + if err != nil { + t.Fatal(err) + } + + c, err := NewClient(WithBaseURL(baseURL)) + if err != nil { + t.Fatal(err) + } + + if _, err := c.GetStatement(t.Context(), nil); err == nil { + t.Fatal("expected error") + } else if !errors.Is(err, api.ErrUnknownContentType) { + t.Fatalf("want: %v, got: %v", api.ErrUnknownContentType, err) + } + }) + + t.Run("decoding error", func(t *testing.T) { + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, http.StatusOK, "text/xml", []byte("")))) + if err != nil { + t.Fatal(err) + } + + if _, err := c.GetStatement(t.Context(), nil); err == nil { + t.Fatal("expected error") + } else if decErr, ok := errors.AsType[*api.DecodingError](err); !ok { + t.Fatalf("got: %T, want: *api.DecodingError", err) + } else if _, ok := errors.AsType[*xml.SyntaxError](decErr.Err); !ok { + t.Fatalf("got: %T, want: *xml.SyntaxError", decErr.Err) + } + }) + }) + t.Run("GetPage", func(t *testing.T) { t.Run("transport error", func(t *testing.T) { c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( @@ -2212,6 +2293,32 @@ func TestClient_Error(t *testing.T) { // TestClient_Params sets every parameter it can to a value other than its zero value, and finds each in the request, // under its name and written as the client must write it. func TestClient_Params(t *testing.T) { + t.Run("GetStatement", func(t *testing.T) { + var got *http.Request + + c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( + func(r *http.Request) (*http.Response, error) { + got = r + + return &http.Response{StatusCode: http.StatusTeapot, Header: http.Header{}, Body: http.NoBody, Request: r}, nil + }, + )})) + if err != nil { + t.Fatal(err) + } + + _, _ = c.GetStatement(t.Context(), &GetStatementParams{ + Q: "q", + }) + + if got == nil { + t.Fatal("no request was sent") + } + + if v := got.URL.Query().Get("q"); v != "q" { + t.Errorf("query %s: got %q, want %q", "q", v, "q") + } + }) t.Run("ListEntries", func(t *testing.T) { var got *http.Request @@ -2480,4 +2587,16 @@ func TestClient_Interactions(t *testing.T) { }); err != nil { t.Fatalf("QueryStyles: %v", err) } + + if _, err := c.GetStatement(ctx, &GetStatementParams{ + Q: "1", + }); err != nil { + t.Fatalf("GetStatement: %v", err) + } + + if _, err := c.GetStatement(ctx, &GetStatementParams{ + Q: "2", + }); err != nil { + t.Fatalf("GetStatement: %v", err) + } } diff --git a/testdata/golden/pkg/golden/ir.json b/testdata/golden/pkg/golden/ir.json index 22981a57..3834e5f3 100644 --- a/testdata/golden/pkg/golden/ir.json +++ b/testdata/golden/pkg/golden/ir.json @@ -9,6 +9,45 @@ }, "userAgent": "Golden", "operations": [ + { + "name": "GetStatement", + "description": "An XML response is decoded with encoding/xml into the type its schema says: the root element, an attribute, child elements, a list whose items stand side by side, a wrapped list, and the elements only an error answer holds, which may be left out.", + "method": "GET", + "pathTemplate": "/statements", + "joinPathArgs": [ + "\"statements\"" + ], + "queryParams": [ + { + "varName": "params.Q", + "goName": "q", + "fieldName": "Q", + "jsonName": "q", + "type": "string", + "parseExpr": "%s", + "parseErrFree": true + } + ], + "hasParams": true, + "paramStructName": "GetStatementParams", + "responses": [ + { + "statusCode": "200", + "goConstant": "http.StatusOK", + "description": "OK", + "contentType": "text/xml", + "goType": { + "name": "FlexStatementResponse" + }, + "isSuccess": true, + "isXML": true + } + ], + "successReturn": { + "name": "FlexStatementResponse" + }, + "xmlSuccess": true + }, { "name": "GetPage", "summary": "Retrieve a page", @@ -2373,6 +2412,62 @@ } ] }, + { + "name": "FlexStatementResponse", + "description": "FlexStatementResponse defines a model", + "fields": [ + { + "name": "Timestamp", + "jsonName": "timestamp", + "type": "string", + "jsonTag": "json:\"timestamp\" xml:\"timestamp,attr\"", + "required": true + }, + { + "name": "Status", + "jsonName": "Status", + "type": "string", + "jsonTag": "json:\"Status\" xml:\"Status\"", + "required": true + }, + { + "name": "ReferenceCode", + "jsonName": "ReferenceCode", + "type": "string", + "jsonTag": "json:\"ReferenceCode,omitzero\" xml:\"ReferenceCode,omitempty\"" + }, + { + "name": "URL", + "jsonName": "Url", + "type": "string", + "jsonTag": "json:\"Url,omitzero\" xml:\"Url,omitempty\"" + }, + { + "name": "Note", + "jsonName": "Note", + "type": "[]string", + "jsonTag": "json:\"Note,omitzero\" xml:\"Note,omitempty\"" + }, + { + "name": "Books", + "jsonName": "Books", + "type": "[]string", + "jsonTag": "json:\"Books,omitzero\" xml:\"Books>Book,omitempty\"" + }, + { + "name": "ErrorCode", + "jsonName": "ErrorCode", + "type": "string", + "jsonTag": "json:\"ErrorCode,omitzero\" xml:\"ErrorCode,omitempty\"" + }, + { + "name": "ErrorMessage", + "jsonName": "ErrorMessage", + "type": "string", + "jsonTag": "json:\"ErrorMessage,omitzero\" xml:\"ErrorMessage,omitempty\"" + } + ] + }, { "name": "FolderDetails", "description": "FolderDetails defines a model", diff --git a/testdata/golden/pkg/golden/server.gen.go b/testdata/golden/pkg/golden/server.gen.go index 699f69b7..747acff9 100644 --- a/testdata/golden/pkg/golden/server.gen.go +++ b/testdata/golden/pkg/golden/server.gen.go @@ -5,6 +5,7 @@ package golden import ( "context" "encoding/json/v2" + "encoding/xml" "errors" "fmt" "io" @@ -23,6 +24,7 @@ import ( // Service defines the operations the server must implement. type Service interface { + GetStatement(ctx context.Context, params *GetStatementParams) (*FlexStatementResponse, error) GetPage(ctx context.Context, id string) (*Page, error) Search(ctx context.Context, body PropertyFilter) (PageOrPartials, error) GetTrial(ctx context.Context, id string) (*Trial, error) @@ -51,6 +53,56 @@ type Service interface { // RegisterService registers a [Service] with an [*http.ServeMux]. // Optionally, a path prefix may be provided. func RegisterService(svc Service, mux *http.ServeMux, pathPrefix string) { + { + path := fmt.Sprintf("%s%s", pathPrefix, "/statements") + l := slog.Default().With(slog.String("method", "GET"), slog.String("path", path), slog.String("function", "GetStatement")) + + mux.HandleFunc(fmt.Sprintf("GET %s", path), func(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + l.DebugContext(ctx, "called") + + params, err := parseGetStatementArgs(r) + if err != nil { + msg := err.Error() + l.DebugContext(ctx, "Bad Request", slog.String("msg", msg)) + http.Error(w, msg, http.StatusBadRequest) + return + } + + res, err := svc.GetStatement(ctx, ¶ms) + if err != nil { + sErr, ok := errors.AsType[*server.Error](err) + if !ok { + l.ErrorContext(ctx, "Internal Server Error", slog.String("error", err.Error())) + http.Error(w, "Internal Server Error", http.StatusInternalServerError) + return + } + + l.DebugContext(ctx, "graceful error", slog.String("error", err.Error())) + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(sErr.Code) + + if err := json.MarshalWrite(w, err); err != nil { + l.ErrorContext(ctx, "marshal error", slog.String("error", err.Error())) + http.Error(w, "Internal Server Error", http.StatusInternalServerError) + } + return + } + + w.Header().Set("Content-Type", "text/xml") + w.WriteHeader(http.StatusOK) + + if err := xml.NewEncoder(w).Encode(res); err != nil { + l.ErrorContext(ctx, "marshal error", slog.String("error", err.Error())) + http.Error(w, "Internal Server Error", http.StatusInternalServerError) + return + } + + l.DebugContext(ctx, "success") + }) + } + { path := fmt.Sprintf("%s%s", pathPrefix, "/pages/{id}") l := slog.Default().With(slog.String("method", "GET"), slog.String("path", path), slog.String("function", "GetPage")) @@ -1087,6 +1139,16 @@ func RegisterService(svc Service, mux *http.ServeMux, pathPrefix string) { } } +// parseGetStatementArgs reads the path and query parameters of GetStatement from req. +func parseGetStatementArgs(req *http.Request) (params GetStatementParams, err error) { + query := req.URL.Query() + + if s := query.Get("q"); s != "" { + params.Q = s + } + return params, nil +} + // parseListEntriesArgs reads the path and query parameters of ListEntries from req. func parseListEntriesArgs(req *http.Request) (params ListEntriesParams, err error) { query := req.URL.Query() diff --git a/testdata/golden/pkg/golden/types.gen.go b/testdata/golden/pkg/golden/types.gen.go index 71e4efb7..707d1955 100644 --- a/testdata/golden/pkg/golden/types.gen.go +++ b/testdata/golden/pkg/golden/types.gen.go @@ -103,6 +103,11 @@ var jsonOptsResponse = json.JoinOptions(jsonOpts, json.WithMarshalers(json.JoinM }), ))) +// GetStatementParams holds the query parameters for GetStatement. +type GetStatementParams struct { + Q string +} + // ListEntriesParams holds the query parameters for ListEntries. type ListEntriesParams struct { StartCursor uuid.UUID @@ -932,6 +937,18 @@ type FilterAnyOf1 struct { And []string `json:"and"` } +// FlexStatementResponse defines a model +type FlexStatementResponse struct { + Timestamp string `json:"timestamp" xml:"timestamp,attr"` + Status string `json:"Status" xml:"Status"` + ReferenceCode string `json:"ReferenceCode,omitzero" xml:"ReferenceCode,omitempty"` + URL string `json:"Url,omitzero" xml:"Url,omitempty"` + Note []string `json:"Note,omitzero" xml:"Note,omitempty"` + Books []string `json:"Books,omitzero" xml:"Books>Book,omitempty"` + ErrorCode string `json:"ErrorCode,omitzero" xml:"ErrorCode,omitempty"` + ErrorMessage string `json:"ErrorMessage,omitzero" xml:"ErrorMessage,omitempty"` +} + // FolderDetails defines a model type FolderDetails struct { Name string `json:"name"` diff --git a/testdata/golden/pkg/golden/xml_test.go b/testdata/golden/pkg/golden/xml_test.go new file mode 100644 index 00000000..abcd9965 --- /dev/null +++ b/testdata/golden/pkg/golden/xml_test.go @@ -0,0 +1,76 @@ +// This file is written by hand, not by the generator. +// +// It pins what the client decodes from an XML response: the attribute, the child elements, a list whose items stand +// side by side and one wrapped in an element of its own, and the elements only an error answer holds. + +package golden + +import ( + "net/http" + "reflect" + "testing" + + "github.com/go-api-libs/api/apitest" +) + +func TestGetStatement_XML(t *testing.T) { + t.Parallel() + + for _, tc := range []struct { + name string + body string + want FlexStatementResponse + }{ + { + name: "success", + body: ` +Success +0877097094 +https://example.com/GetStatement +first +second +ab +`, + want: FlexStatementResponse{ + Timestamp: "27 November, 2026 10:04 AM EST", + Status: "Success", + ReferenceCode: "0877097094", + URL: "https://example.com/GetStatement", + Note: []string{"first", "second"}, + Books: []string{"a", "b"}, + }, + }, + { + name: "an error answer", + body: ` +Fail +1019 +Statement generation in progress. Please try again shortly. +`, + want: FlexStatementResponse{ + Timestamp: "27 November, 2026 10:05 AM EST", + Status: "Fail", + ErrorCode: "1019", + ErrorMessage: "Statement generation in progress. Please try again shortly.", + }, + }, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, http.StatusOK, "text/xml;charset=UTF-8", []byte(tc.body)))) + if err != nil { + t.Fatal(err) + } + + got, err := c.GetStatement(t.Context(), nil) + if err != nil { + t.Fatal(err) + } + + if !reflect.DeepEqual(*got, tc.want) { + t.Errorf("got %+v, want %+v", *got, tc.want) + } + }) + } +} diff --git a/vendor/github.com/MarkRosemaker/cassette/interaction.go b/vendor/github.com/MarkRosemaker/cassette/interaction.go index 649dffc6..68fe9e97 100644 --- a/vendor/github.com/MarkRosemaker/cassette/interaction.go +++ b/vendor/github.com/MarkRosemaker/cassette/interaction.go @@ -5,6 +5,7 @@ import ( "cmp" "context" "encoding/json/jsontext" + "encoding/json/v2" "io" "net/http" "net/url" @@ -153,6 +154,48 @@ func NewResponse(resp *http.Response) (Response, error) { // Body is a recorded body: written as the JSON it is, or as a string if it is no JSON. type Body []byte +// UnmarshalJSONFrom implements [json.UnmarshalerFrom]: a body of text, such as XML or HTML, written as a JSON string +// is read back as the text it is, as it was sent, not as the JSON string it was written as. +func (r *Request) UnmarshalJSONFrom(dec *jsontext.Decoder) error { + type plain Request + + if err := json.UnmarshalDecode(dec, (*plain)(r)); err != nil { + return err + } + + r.Body = r.Body.asSent(r.Headers.Get("Content-Type")) + + return nil +} + +// UnmarshalJSONFrom implements [json.UnmarshalerFrom], reading a body of text as [Request.UnmarshalJSONFrom] does. +func (rsp *Response) UnmarshalJSONFrom(dec *jsontext.Decoder) error { + type plain Response + + if err := json.UnmarshalDecode(dec, (*plain)(rsp)); err != nil { + return err + } + + rsp.Body = rsp.Body.asSent(rsp.Headers.Get("Content-Type")) + + return nil +} + +// asSent is b as it was sent with contentType: a JSON string, which is how a body of text other than JSON is written, +// is the text it holds. A body of JSON, or of no content type said, is the JSON it is. +func (b Body) asSent(contentType string) Body { + if contentType == "" || isJSON(contentType) || jsontext.Value(b).Kind() != '"' { + return b + } + + text, err := jsontext.AppendUnquote(nil, []byte(b)) + if err != nil { + return b + } + + return text +} + // IsZero reports whether there is no body, which is left out when written: an empty JSON value, such as null or {}, // is a body all the same. func (b Body) IsZero() bool { return len(b) == 0 } diff --git a/vendor/github.com/MarkRosemaker/cassette/large.go b/vendor/github.com/MarkRosemaker/cassette/large.go index ca29a7bd..cccf377e 100644 --- a/vendor/github.com/MarkRosemaker/cassette/large.go +++ b/vendor/github.com/MarkRosemaker/cassette/large.go @@ -36,6 +36,13 @@ func IsText(contentType string) bool { } } +// isJSON reports whether contentType is a JSON media type. One that does not parse is not. +func isJSON(contentType string) bool { + mt, _, err := mime.ParseMediaType(contentType) + + return err == nil && (mt == "application/json" || strings.HasSuffix(mt, "+json") || strings.Contains(mt, "/json")) +} + // TrimBodies omits every recorded body that is not text, see [IsText], and cuts every JSON string in the others // longer than maxLen bytes, see [MaxStringLen]. func (ias Interactions) TrimBodies(maxLen int) { diff --git a/vendor/github.com/MarkRosemaker/openapi/schema.go b/vendor/github.com/MarkRosemaker/openapi/schema.go index 433f2b80..c9bf9376 100644 --- a/vendor/github.com/MarkRosemaker/openapi/schema.go +++ b/vendor/github.com/MarkRosemaker/openapi/schema.go @@ -107,6 +107,8 @@ type Schema struct { PropertyNames *Schema `json:"propertyNames,omitzero" yaml:"propertyNames,omitempty"` // Tells which of the composed schemas a payload is, by the value of one of its properties. Discriminator *Discriminator `json:"discriminator,omitzero" yaml:"discriminator,omitempty"` + // How the schema is written as XML. + XML *XML `json:"xml,omitzero" yaml:"xml,omitempty"` // special encoding for binary data ContentMediaType string `json:"contentMediaType,omitempty" yaml:"contentMediaType,omitempty"` @@ -179,6 +181,7 @@ func (s *Schema) validate(extended bool) error { s.validateArray, s.validateObject, func() error { return s.validateDiscriminator(extended) }, + s.validateXML, s.validateDefault, } { if err := check(); err != nil { @@ -521,6 +524,19 @@ func (s *Schema) validateObject() error { return nil } +// validateXML checks how the schema is written as XML, if it says. +func (s *Schema) validateXML() error { + if s.XML == nil { + return nil + } + + if err := s.XML.Validate(); err != nil { + return &errpath.ErrField{Field: "xml", Err: err} + } + + return nil +} + // validateDiscriminator checks where the discriminator may be: beside a composition, or on a parent another schema // extends through allOf. func (s *Schema) validateDiscriminator(extended bool) error { diff --git a/vendor/github.com/MarkRosemaker/openapi/xml.go b/vendor/github.com/MarkRosemaker/openapi/xml.go new file mode 100644 index 00000000..0fe1a319 --- /dev/null +++ b/vendor/github.com/MarkRosemaker/openapi/xml.go @@ -0,0 +1,41 @@ +package openapi + +import ( + "net/url" + + "github.com/MarkRosemaker/errpath" +) + +// XML says how a schema is written as XML: the name of its element or attribute, its namespace, and whether it is an +// attribute or, for a list, wrapped in an element of its own. ([Specification]) +// +// [Specification]: https://spec.openapis.org/oas/v3.1.0#xml-object +type XML struct { + // The name of the element or attribute, in place of the property's or, for a list's items, the list's. + Name string `json:"name,omitempty" yaml:"name,omitempty"` + // The absolute URI of the namespace. + Namespace string `json:"namespace,omitempty" yaml:"namespace,omitempty"` + // The prefix of the name. + Prefix string `json:"prefix,omitempty" yaml:"prefix,omitempty"` + // Whether the property is an attribute of its element rather than an element of its own. + Attribute bool `json:"attribute,omitzero" yaml:"attribute,omitempty"` + // Whether a list is wrapped in an element of its own, as , rather than its items + // standing side by side. + Wrapped bool `json:"wrapped,omitzero" yaml:"wrapped,omitempty"` + // This object MAY be extended with Specification Extensions. + Extensions Extensions `json:",embed" yaml:",embed"` +} + +// Validate checks the XML object for correctness. +func (x *XML) Validate() error { + if x.Namespace != "" { + if u, err := url.Parse(x.Namespace); err != nil || !u.IsAbs() { + return &errpath.ErrField{Field: "namespace", Err: &errpath.ErrInvalid[string]{ + Value: x.Namespace, + Message: "must be an absolute URI", + }} + } + } + + return validateExtensions(x.Extensions) +} diff --git a/vendor/modules.txt b/vendor/modules.txt index 1a4b7e70..e5b4c065 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -1,7 +1,7 @@ # cloud.google.com/go v0.123.0 ## explicit; go 1.24.0 cloud.google.com/go/civil -# github.com/MarkRosemaker/cassette v0.0.0-20261127001959-2e9c977b04a7 +# github.com/MarkRosemaker/cassette v0.0.0-20261127153817-bd6de8a6d78a ## explicit; go 1.27 github.com/MarkRosemaker/cassette # github.com/MarkRosemaker/errpath v0.0.0-20261127001931-41afc0b86075 @@ -13,7 +13,7 @@ github.com/MarkRosemaker/json2yaml # github.com/MarkRosemaker/jsonutil v0.0.0-20261127001933-b07dbcceebd6 ## explicit; go 1.27 github.com/MarkRosemaker/jsonutil -# github.com/MarkRosemaker/openapi v0.0.0-20261127002030-cbffd96bf394 +# github.com/MarkRosemaker/openapi v0.0.0-20261127152632-cf3bbccfbf2b ## explicit; go 1.27 github.com/MarkRosemaker/openapi # github.com/MarkRosemaker/openapi-compare v0.0.0-20261127002121-d284f72800b7 From b1e31f32a7d3a86d51e42c1c6c6a6a714dec073a Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 15:51:49 +0000 Subject: [PATCH 2/2] chore: pin openapi and cassette to their default branches, which have the xml object and text replay Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019QCb1AfnATvpBQCH3PrX7Y --- go.mod | 4 ++-- go.sum | 8 ++++---- vendor/modules.txt | 4 ++-- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/go.mod b/go.mod index 0fb2ec9b..51e30173 100644 --- a/go.mod +++ b/go.mod @@ -3,9 +3,9 @@ module github.com/MarkRosemaker/openapi-codegen go 1.27 require ( - github.com/MarkRosemaker/cassette v0.0.0-20261127153817-bd6de8a6d78a + github.com/MarkRosemaker/cassette v0.0.0-20261127154835-ca0fcfc2eb8f github.com/MarkRosemaker/errpath v0.0.0-20261127001931-41afc0b86075 - github.com/MarkRosemaker/openapi v0.0.0-20261127152632-cf3bbccfbf2b + github.com/MarkRosemaker/openapi v0.0.0-20261127155054-78507e678e58 github.com/MarkRosemaker/openapi-compress v0.0.0-20261127050502-a5e936024b23 github.com/MarkRosemaker/openapi-edit v0.0.0-20261127002121-4ed97994dce4 github.com/MarkRosemaker/openapi-flatten v0.0.0-20261127002122-68a4af5d679f diff --git a/go.sum b/go.sum index 09c65b3c..762e00aa 100644 --- a/go.sum +++ b/go.sum @@ -1,15 +1,15 @@ cloud.google.com/go v0.123.0 h1:2NAUJwPR47q+E35uaJeYoNhuNEM9kM8SjgRgdeOJUSE= cloud.google.com/go v0.123.0/go.mod h1:xBoMV08QcqUGuPW65Qfm1o9Y4zKZBpGS+7bImXLTAZU= -github.com/MarkRosemaker/cassette v0.0.0-20261127153817-bd6de8a6d78a h1:tXWY98FzOSj7ZZlo4xYN5Xh2Nl3r2mOU22lbN2KAMfQ= -github.com/MarkRosemaker/cassette v0.0.0-20261127153817-bd6de8a6d78a/go.mod h1:VC3Nc2r+4OJ1c6gRtJjs4H4jp0Iy11PbLPkys6+O/Y4= +github.com/MarkRosemaker/cassette v0.0.0-20261127154835-ca0fcfc2eb8f h1:GNwVBRdA8+F7c5+wNEGRhHwemA4wutGfrpvaiQ38TCU= +github.com/MarkRosemaker/cassette v0.0.0-20261127154835-ca0fcfc2eb8f/go.mod h1:VC3Nc2r+4OJ1c6gRtJjs4H4jp0Iy11PbLPkys6+O/Y4= github.com/MarkRosemaker/errpath v0.0.0-20261127001931-41afc0b86075 h1:qJS31SpFD4TSnn2cOfh7n3dhsyUleXsl0o+Svo4JzMk= github.com/MarkRosemaker/errpath v0.0.0-20261127001931-41afc0b86075/go.mod h1:VnXpUlsS3n1gSToedcQl2FCARGoA16CyitbCanUIv+I= github.com/MarkRosemaker/json2yaml v0.0.0-20261127001931-55b661ab603c h1:t+nWAPGKlpQTpcDVessJk4Jl1PABKdeO3bdEFisb1pY= github.com/MarkRosemaker/json2yaml v0.0.0-20261127001931-55b661ab603c/go.mod h1:eUwIjjooIESK1Ymw4bbMdSDF6feAblyZjxyoo5o/W6U= github.com/MarkRosemaker/jsonutil v0.0.0-20261127001933-b07dbcceebd6 h1:gLKnOUYT7pbfbTyE+uyZOtuK0HJXbE6K3ULP5Vr9hFk= github.com/MarkRosemaker/jsonutil v0.0.0-20261127001933-b07dbcceebd6/go.mod h1:SzjJlgYFlzpbFGvUUoQgfEsWlbai63bvhDPK8J0MNYM= -github.com/MarkRosemaker/openapi v0.0.0-20261127152632-cf3bbccfbf2b h1:EwF9SivYmofrwTmxrwKe9Ctgsa8kYNSotwvzPA2X6IM= -github.com/MarkRosemaker/openapi v0.0.0-20261127152632-cf3bbccfbf2b/go.mod h1:yrht5AwFPmZzg7PxpNesNN5EqdPEZ/aUw7DC6zIO75o= +github.com/MarkRosemaker/openapi v0.0.0-20261127155054-78507e678e58 h1:JM+IezX97aVNtZDIu4lxCjTG7/nmAhecetuDdrSyMyI= +github.com/MarkRosemaker/openapi v0.0.0-20261127155054-78507e678e58/go.mod h1:yrht5AwFPmZzg7PxpNesNN5EqdPEZ/aUw7DC6zIO75o= github.com/MarkRosemaker/openapi-compare v0.0.0-20261127002121-d284f72800b7 h1:1EOen5YicLT0hb73OFD9BYfV4pkrFA/BKxOQNOVhaqo= github.com/MarkRosemaker/openapi-compare v0.0.0-20261127002121-d284f72800b7/go.mod h1:YKLfAnLhQ1OJ6/Qw9ECIx1ksyIwJ1hFEhcmfahGy/9E= github.com/MarkRosemaker/openapi-compress v0.0.0-20261127050502-a5e936024b23 h1:FDKq/Kcpgaghk25mWCx99D4r+jBzm+KcyTh2OXO3lAI= diff --git a/vendor/modules.txt b/vendor/modules.txt index e5b4c065..82a7a602 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -1,7 +1,7 @@ # cloud.google.com/go v0.123.0 ## explicit; go 1.24.0 cloud.google.com/go/civil -# github.com/MarkRosemaker/cassette v0.0.0-20261127153817-bd6de8a6d78a +# github.com/MarkRosemaker/cassette v0.0.0-20261127154835-ca0fcfc2eb8f ## explicit; go 1.27 github.com/MarkRosemaker/cassette # github.com/MarkRosemaker/errpath v0.0.0-20261127001931-41afc0b86075 @@ -13,7 +13,7 @@ github.com/MarkRosemaker/json2yaml # github.com/MarkRosemaker/jsonutil v0.0.0-20261127001933-b07dbcceebd6 ## explicit; go 1.27 github.com/MarkRosemaker/jsonutil -# github.com/MarkRosemaker/openapi v0.0.0-20261127152632-cf3bbccfbf2b +# github.com/MarkRosemaker/openapi v0.0.0-20261127155054-78507e678e58 ## explicit; go 1.27 github.com/MarkRosemaker/openapi # github.com/MarkRosemaker/openapi-compare v0.0.0-20261127002121-d284f72800b7