oapi-codegen
oapi-codegen copied to clipboard
Strict server code generator does not handle properly union type
When schema object is defined as oneOf or anyOf, the server generator creates it as a struct with a union field and json.RawMessage type value.
Example:
type Config struct {
union json.RawMessage
}
In case this object is returned in create/get/update api application/json response , the generator creates a visitor function that encodes the response object as JSON. This is returning an empty json result.
func (response CreateConfig201JSONResponse) VisitCreateConfigResponse(w http.ResponseWriter) error {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(201)
return json.NewEncoder(w).Encode(response)
}
To return the object JSON content, the visitor function should encode the response.union field instead. This manual workaround returned the expected result:
func (response CreateConfig201JSONResponse) VisitCreateConfigResponse(w http.ResponseWriter) error {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(201)
return json.NewEncoder(w).Encode(response.union)
}
go version go1.18.4 darwin/arm64
oapi-codegen --version
github.com/deepmap/oapi-codegen/cmd/oapi-codegen
v1.11.1-0.20220908201945-d1a63c702fd0