diff --git a/README.md b/README.md index 3e0fba8ec..b7b93875c 100644 --- a/README.md +++ b/README.md @@ -474,6 +474,10 @@ which help you to use the various OpenAPI 3 Authentication mechanism. will override any default value. This extended property isn't supported in all parts of OpenAPI, so please refer to the spec as to where it's allowed. Swagger validation tools will flag incorrect usage of this property. +- `x-go-name`: specifies Go field name. It allows you to specify the field name for a schema, and + will override any default value. This extended property isn't supported in all parts of + OpenAPI, so please refer to the spec as to where it's allowed. Swagger validation tools will + flag incorrect usage of this property. - `x-oapi-codegen-extra-tags`: adds extra Go field tags to the generated struct field. This is useful for interfacing with tag based ORM or validation libraries. The extra tags that are added are in addition to the regular json tags that are generated. If you specify your diff --git a/pkg/codegen/extension.go b/pkg/codegen/extension.go index 89d85fa79..28294b196 100644 --- a/pkg/codegen/extension.go +++ b/pkg/codegen/extension.go @@ -7,21 +7,29 @@ import ( const ( extPropGoType = "x-go-type" + extGoFieldName = "x-go-name" extPropOmitEmpty = "x-omitempty" extPropExtraTags = "x-oapi-codegen-extra-tags" ) -func extTypeName(extPropValue interface{}) (string, error) { +func extString(extPropValue interface{}) (string, error) { raw, ok := extPropValue.(json.RawMessage) if !ok { return "", fmt.Errorf("failed to convert type: %T", extPropValue) } - var name string - if err := json.Unmarshal(raw, &name); err != nil { + var str string + if err := json.Unmarshal(raw, &str); err != nil { return "", fmt.Errorf("failed to unmarshal json: %w", err) } - return name, nil + return str, nil +} +func extTypeName(extPropValue interface{}) (string, error) { + return extString(extPropValue) +} + +func extParseGoFieldName(extPropValue interface{}) (string, error) { + return extString(extPropValue) } func extParseOmitEmpty(extPropValue interface{}) (bool, error) { diff --git a/pkg/codegen/schema.go b/pkg/codegen/schema.go index 1ee521cef..b5aca0a5d 100644 --- a/pkg/codegen/schema.go +++ b/pkg/codegen/schema.go @@ -432,7 +432,15 @@ func GenFieldsFromProperties(props []Property) []string { } field += fmt.Sprintf("%s\n", StringToGoComment(p.Description)) } - field += fmt.Sprintf(" %s %s", p.GoFieldName(), p.GoTypeDef()) + + goFieldName := p.GoFieldName() + if _, ok := p.ExtensionProps.Extensions[extGoFieldName]; ok { + if extGoFieldName, err := extParseGoFieldName(p.ExtensionProps.Extensions[extGoFieldName]); err == nil { + goFieldName = extGoFieldName + } + } + + field += fmt.Sprintf(" %s %s", goFieldName, p.GoTypeDef()) // Support x-omitempty omitEmpty := true