You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
From a project I've done this in before, I get the following generated:
// AsJSONPatchRequestAddReplaceTest returns the union data inside the PatchRequest_Item as a JSONPatchRequestAddReplaceTestfunc (tPatchRequest_Item) AsJSONPatchRequestAddReplaceTest() (JSONPatchRequestAddReplaceTest, error) {
varbodyJSONPatchRequestAddReplaceTesterr:=json.Unmarshal(t.union, &body)
returnbody, err
}
// FromJSONPatchRequestAddReplaceTest overwrites any union data inside the PatchRequest_Item as the provided JSONPatchRequestAddReplaceTestfunc (t*PatchRequest_Item) FromJSONPatchRequestAddReplaceTest(vJSONPatchRequestAddReplaceTest) error {
b, err:=json.Marshal(v)
t.union=breturnerr
}
// MergeJSONPatchRequestAddReplaceTest performs a merge with any union data inside the PatchRequest_Item, using the provided JSONPatchRequestAddReplaceTestfunc (t*PatchRequest_Item) MergeJSONPatchRequestAddReplaceTest(vJSONPatchRequestAddReplaceTest) error {
b, err:=json.Marshal(v)
iferr!=nil {
returnerr
}
merged, err:=runtime.JsonMerge(b, t.union)
t.union=mergedreturnerr
}
You should be able to use these to set the type based on your orderResponseAck, etc.
It's unfortunately not a super great solution (I wrote it 😅) but as we don't have union types in Go, this was the option we went for
From a project I've done this in before, I get the following generated:
// AsJSONPatchRequestAddReplaceTest returns the union data inside the PatchRequest_Item as a JSONPatchRequestAddReplaceTestfunc (tPatchRequest_Item) AsJSONPatchRequestAddReplaceTest() (JSONPatchRequestAddReplaceTest, error) {
varbodyJSONPatchRequestAddReplaceTesterr:=json.Unmarshal(t.union, &body)
returnbody, err
}
// FromJSONPatchRequestAddReplaceTest overwrites any union data inside the PatchRequest_Item as the provided JSONPatchRequestAddReplaceTestfunc (t*PatchRequest_Item) FromJSONPatchRequestAddReplaceTest(vJSONPatchRequestAddReplaceTest) error {
b, err:=json.Marshal(v)
t.union=breturnerr
}
// MergeJSONPatchRequestAddReplaceTest performs a merge with any union data inside the PatchRequest_Item, using the provided JSONPatchRequestAddReplaceTestfunc (t*PatchRequest_Item) MergeJSONPatchRequestAddReplaceTest(vJSONPatchRequestAddReplaceTest) error {
b, err:=json.Marshal(v)
iferr!=nil {
returnerr
}
merged, err:=runtime.JsonMerge(b, t.union)
t.union=mergedreturnerr
}
You should be able to use these to set the type based on your orderResponseAck, etc.
It's unfortunately not a super great solution (I wrote it 😅) but as we don't have union types in Go, this was the option we went for
i cant access union field because I place generated code in separete package. So I need to write additional functions in this package that will fill union field with data?
No, you're not expected to manually interact with the union field, you should use the helper methods that are generated - hopefully PostFapiV1Order200JSONResponse should have other methods generated for it.
If not (and you're running latest oapi-codegen version) then it may be you need to move the type to /components/schemas to get the generation working, but that'll provide you helper methods like As..., From... and Merge... to make it possible
openapi: 3.0.3info:
description: test serverversion: 1.0.0paths:
/tickets/{ticket_id}/accept:
post:
operationId: acceptTicketsecurity:
- RoleAuth:
- adminsummary: Accept a requested or reapplied Account Ticketparameters:
- $ref: '#/components/parameters/ticketIdParam'tags:
- Account Ticketsresponses:
'200':
description: Returns Account if the ticket was Reapply otherwise the AccountTicketcontent:
application/json:
schema:
$ref: '#/components/schemas/AcceptTicketResponse'components:
schemas:
AcceptTicketResponse:
oneOf:
- $ref: '#/components/schemas/Account'
- $ref: '#/components/schemas/AccountTicket'Account:
properties:
id:
type: integerAccountTicket:
properties:
ticket_id:
type: integer
It generates ok code, but the decoder for VisitAcceptTicket does not decode the union but the type itself, returning an empty object.
Generated code:
typeAcceptTicket200JSONResponseAcceptTicketResponse// AcceptTicketResponse defines model for AcceptTicketResponse.typeAcceptTicketResponsestruct {
union json.RawMessage
}
// AcceptTicketResponse0 defines model for .typeAcceptTicketResponse0struct {
Namestring`json:"name"`
}
// AcceptTicketResponse1 defines model for .typeAcceptTicketResponse1struct {
Name2string`json:"name2"`
}
// AsAcceptTicketResponse0 returns the union data inside the AcceptTicketResponse as a AcceptTicketResponse0func (tAcceptTicketResponse) AsAcceptTicketResponse0() (AcceptTicketResponse0, error) {
varbodyAcceptTicketResponse0err:=json.Unmarshal(t.union, &body)
returnbody, err
}
// FromAcceptTicketResponse0 overwrites any union data inside the AcceptTicketResponse as the provided AcceptTicketResponse0func (t*AcceptTicketResponse) FromAcceptTicketResponse0(vAcceptTicketResponse0) error {
b, err:=json.Marshal(v)
t.union=breturnerr
}
// MergeAcceptTicketResponse0 performs a merge with any union data inside the AcceptTicketResponse, using the provided AcceptTicketResponse0func (t*AcceptTicketResponse) MergeAcceptTicketResponse0(vAcceptTicketResponse0) error {
b, err:=json.Marshal(v)
iferr!=nil {
returnerr
}
merged, err:=runtime.JsonMerge(t.union, b)
t.union=mergedreturnerr
}
// AsAcceptTicketResponse1 returns the union data inside the AcceptTicketResponse as a AcceptTicketResponse1func (tAcceptTicketResponse) AsAcceptTicketResponse1() (AcceptTicketResponse1, error) {
varbodyAcceptTicketResponse1err:=json.Unmarshal(t.union, &body)
returnbody, err
}
// FromAcceptTicketResponse1 overwrites any union data inside the AcceptTicketResponse as the provided AcceptTicketResponse1func (t*AcceptTicketResponse) FromAcceptTicketResponse1(vAcceptTicketResponse1) error {
b, err:=json.Marshal(v)
t.union=breturnerr
}
// MergeAcceptTicketResponse1 performs a merge with any union data inside the AcceptTicketResponse, using the provided AcceptTicketResponse1func (t*AcceptTicketResponse) MergeAcceptTicketResponse1(vAcceptTicketResponse1) error {
b, err:=json.Marshal(v)
iferr!=nil {
returnerr
}
merged, err:=runtime.JsonMerge(t.union, b)
t.union=mergedreturnerr
}
This can be solved in the same way as proto, interfaces and type switches.
Proto makes each of the oneof structs implement a noop interface, then provides getters and setters. Upon decoding you'd require that people provide a discriminator and that would allow you to generate each struct with a type switch.
This will generate response object with union, and OrderResponse with union and helpers.
Then just cast OrderResponse to response object before returning from handler.
The issue reported that inline oneOf response schemas lacked As/From/Merge accessor methods and that the strict-server Visit method encoded the wrapper struct (emitting '{}') instead of the .union field. Commit 81b9d95 (PR #2348, 'Overhaul anonymous schema hoisting') explicitly fixes this: boilerplateTypes now includes response AdditionalTypeDefinitions so union accessors are emitted for inline schemas, and a named type (PostFapiV1Order200JSONResponseBody) replaces the anonymous struct so methods can be bound. Running the exact spec from the issue against the current binary confirms full As/From/Merge generation and correct union encoding in VisitPostFapiV1OrderResponse.
Closing as fixed. If you can still reproduce on a recent release, please reopen with the exact spec and version used.
Activity
jamietanna commentedon Jun 29, 2023
From a project I've done this in before, I get the following generated:
You should be able to use these to set the type based on your
orderResponseAck, etc.It's unfortunately not a super great solution (I wrote it 😅) but as we don't have union types in Go, this was the option we went for
tandem97 commentedon Jun 29, 2023
i cant access union field because I place generated code in separete package. So I need to write additional functions in this package that will fill union field with data?
jamietanna commentedon Jun 29, 2023
No, you're not expected to manually interact with the
unionfield, you should use the helper methods that are generated - hopefullyPostFapiV1Order200JSONResponseshould have other methods generated for it.If not (and you're running latest
oapi-codegenversion) then it may be you need to move the type to/components/schemasto get the generation working, but that'll provide you helper methods likeAs...,From...andMerge...to make it possibletandem97 commentedon Jun 29, 2023
//go:generate oapi-codegen --package api -o ./api/server.gen.go --generate chi-server,strict-server,spec,types ./api.yamlhere is test spec and generate command. I do not have any methods in PostFapiV1Order200JSONResponse
illiafox commentedon Jul 11, 2023
Hi! Did you find a solution?
tandem97 commentedon Jul 12, 2023
No :(
sz-po commentedon Jul 17, 2023
Same here :(
marmiha commentedon Sep 19, 2023
Ive tried to make schema object as such
It generates ok code, but the decoder for VisitAcceptTicket does not decode the union but the type itself, returning an empty object.
Generated code:
and:
but only works if:
marmiha commentedon Sep 19, 2023
It seems to be a problem when you have a content of response of type schema
oneOf:Generates responses as:
which decodes as
{}when:is called.
It would work if we would encode
response.unionand notresponseitself, as the encoding theresponsereturns{}and not the content of the union.Proposal that if the response has
oneOfschema, then encode theresponse.unionand notresponseas the 200 object is a type and not a struct.tandem97 commentedon Sep 28, 2023
The same situation happens when you are using oneOf in request too
pbdeuchler commentedon Oct 17, 2023
This can be solved in the same way as proto, interfaces and type switches.
Proto makes each of the
oneofstructs implement a noop interface, then provides getters and setters. Upon decoding you'd require that people provide a discriminator and that would allow you to generate each struct with a type switch.davy-ikv commentedon Mar 6, 2024
I modified template
strict-interface.tmplto insert union helpers:From this line https://github.com/deepmap/oapi-codegen/blob/master/pkg/codegen/templates/strict/strict-interface.tmpl#L52, changes to:
{{else if and (not $hasHeaders) ($fixedStatusCode) (.IsSupported) -}} type {{$receiverTypeName}} {{if eq .NameTag "Multipart"}}func(writer *multipart.Writer)error{{else if .IsSupported}}{{if and .Schema.IsRef (not .Schema.IsExternalRef)}}={{end}} {{.Schema.TypeDecl}}{{else}}io.Reader{{end}} {{/* HACK: generate union helpers for response types */ -}} {{$discriminator := .Schema.Discriminator}} {{$properties := .Schema.Properties -}} {{range .Schema.UnionElements}} {{$element := . -}} // As{{ .Method }} returns the union data inside the {{$receiverTypeName}} as a {{.}} func (t {{$receiverTypeName}}) As{{ .Method }}() ({{.}}, error) { var body {{.}} err := json.Unmarshal(t.union, &body) return body, err } // From{{ .Method }} overwrites any union data inside the {{$receiverTypeName}} as the provided {{.}} func (t *{{$receiverTypeName}}) From{{ .Method }} (v {{.}}) error { {{if $discriminator -}} {{range $value, $type := $discriminator.Mapping -}} {{if eq $type $element -}} {{$hasProperty := false -}} {{range $properties -}} {{if eq .GoFieldName $discriminator.PropertyName -}} t.{{$discriminator.PropertyName}} = "{{$value}}" {{$hasProperty = true -}} {{end -}} {{end -}} {{if not $hasProperty}}v.{{$discriminator.PropertyName}} = "{{$value}}"{{end}} {{end -}} {{end -}} {{end -}} b, err := json.Marshal(v) t.union = b return err } // Merge{{ .Method }} performs a merge with any union data inside the {{$receiverTypeName}}, using the provided {{.}} func (t *{{$receiverTypeName}}) Merge{{ .Method }} (v {{.}}) error { {{if $discriminator -}} {{range $value, $type := $discriminator.Mapping -}} {{if eq $type $element -}} {{$hasProperty := false -}} {{range $properties -}} {{if eq .GoFieldName $discriminator.PropertyName -}} t.{{$discriminator.PropertyName}} = "{{$value}}" {{$hasProperty = true -}} {{end -}} {{end -}} {{if not $hasProperty}}v.{{$discriminator.PropertyName}} = "{{$value}}"{{end}} {{end -}} {{end -}} {{end -}} b, err := json.Marshal(v) if err != nil { return err } merged, err := runtime.JSONMerge(t.union, b) t.union = merged return err } {{end}}Or in other way, you can describe the schema like this:
This will generate response object with union, and
OrderResponsewith union and helpers.Then just cast OrderResponse to response object before returning from handler.
mromaszewicz commentedon May 1, 2026
The issue reported that inline oneOf response schemas lacked As/From/Merge accessor methods and that the strict-server Visit method encoded the wrapper struct (emitting '{}') instead of the .union field. Commit 81b9d95 (PR #2348, 'Overhaul anonymous schema hoisting') explicitly fixes this: boilerplateTypes now includes response AdditionalTypeDefinitions so union accessors are emitted for inline schemas, and a named type (PostFapiV1Order200JSONResponseBody) replaces the anonymous struct so methods can be bound. Running the exact spec from the issue against the current binary confirms full As/From/Merge generation and correct union encoding in VisitPostFapiV1OrderResponse.
Closing as fixed. If you can still reproduce on a recent release, please reopen with the exact spec and version used.