Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 7 additions & 0 deletions README/features.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -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-20261127154835-ca0fcfc2eb8f
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-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
Expand Down
8 changes: 4 additions & 4 deletions go.sum
Original file line number Diff line number Diff line change
@@ -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-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-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-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=
Expand Down
2 changes: 2 additions & 0 deletions ir/document.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
6 changes: 5 additions & 1 deletion ir/ir.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
Expand Down Expand Up @@ -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"`
Expand All @@ -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.
Expand Down
35 changes: 31 additions & 4 deletions ir/operation.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down Expand Up @@ -131,6 +131,7 @@ func FromOperation(
Deprecated: op.Deprecated,
RawBytesSuccess: rawBytesSuccess,
StreamSuccess: streamSuccess,
XMLSuccess: xmlSuccess,
EmptySuccess: emptySuccess,
pagination: pagination,
}, nil
Expand Down Expand Up @@ -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
)

Expand All @@ -760,13 +762,19 @@ 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() {
if firstContentType == "" {
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
Expand All @@ -779,6 +787,7 @@ func fromResponses(responses openapi.OperationResponses) (Responses, *GoType, bo
contentType string
isRawBytes bool
isStream bool
isXML bool
)

switch {
Expand All @@ -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
Expand All @@ -818,6 +838,7 @@ func fromResponses(responses openapi.OperationResponses) (Responses, *GoType, bo
IsSuccess: isSuccess,
IsRawBytes: isRawBytes,
IsStream: isStream,
IsXML: isXML,

BodyDescription: refDescription(jsonSchema),
})
Expand All @@ -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 {
Expand Down Expand Up @@ -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")
}
117 changes: 117 additions & 0 deletions ir/xml.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
1 change: 1 addition & 0 deletions render/imports.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
14 changes: 14 additions & 0 deletions render/templates/client.gen.go.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -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 -}}
Expand Down
19 changes: 18 additions & 1 deletion render/templates/client.gen_test.go.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -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("<unclosed>"))))
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) }}
Expand Down Expand Up @@ -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 -}}
Expand Down
Loading
Loading