oapi-codegen
oapi-codegen copied to clipboard
Option to generate a struct without sorting fields
I want to generate a struct without sorting fields, in the order listed in the OpenAPI doc.
I wrote my OpenAPI component schema so that the fields that are important to the user are at the top And I want to return JSON fields on my server response in the same order. However, for now, generated fields are sorted in increasing order.
So I want an option to generate a struct without sorting field.
openapi.yml
components:
schemas:
Pet:
properties:
id:
type: integer
format: int64
description: Unique id of the pet
name:
type: string
description: Name of the pet
age:
type: integer
format: int64
description: Age of the pet
Current
// Pet defines model for Pet.
type Pet struct {
// Age of the pet
Age *int64 `json:"age,omitempty"`
// Unique id of the pet
Id *int64 `json:"id,omitempty"`
// Name of the pet
Name *string `json:"name,omitempty"`
}
What I want
// Pet defines model for Pet.
type Pet struct {
// Unique id of the pet
Id *int64 `json:"id,omitempty"`
// Name of the pet
Name *string `json:"name,omitempty"`
// Age of the pet
Age *int64 `json:"age,omitempty"`
}
+100 -
great job with oapi-codegen, but we are very irritated to see all the fields from our nicely designed structures appear in alphabetical order...
the underlying https://github.com/getkin/kin-openapi/ seems to be the problem, parsing it into a map where the ordering is lost.
@deepmap-marcinr Is there a way to fix / work around this?
Often this problem is solved by the x-order
extension, for example in https://github.com/go-openapi/spec or https://github.com/go-swagger/go-swagger
I have check dependecy for parsing openapi specification - github.com/getkin/kin-openapi openapi3/schema.go:156 - field that keep properties openapi3/loader.go:159 - unmarshalling yaml to struct
Look like it is a behaviour of "github.com/invopop/yaml" unmarshalling mechanism. I tried "gopkg.in/yaml.v3" , but does not work.
What suggestions how to fix it without writing a new yaml parser?
https://github.com/getkin/kin-openapi did use https://github.com/ghodss/yaml but they switched to https://github.com/invopop/yaml for some reason. https://github.com/ghodss/yaml seems to keep the order of the fields when converted.
Well, it's somewhere inside convertToJSONableObject in invopop/yaml because go-yaml/yaml keeps the ordering when YAML is converted to map.
https://github.com/goccy/go-yaml
This library preserves the order. Would it be enough to replace invopop/yaml with goccy/go-yaml? It has the same function func YAMLToJSON(bytes []byte) ([]byte, error)
The problem is relevant for me too. Are there any solutions?
This also frustrates me the most about the oapi codegen. Are there any workarounds for this?
:eyes: #1190 should be merged today
Closed by https://github.com/deepmap/oapi-codegen/commit/3bf5755366704a1594410d6a7aa7aab966d04c6e (incorrectly attributed commit)