Skip to content

Commit

Permalink
Add x-go-name property extension (#517)
Browse files Browse the repository at this point in the history
  • Loading branch information
emilekm committed Apr 19, 2022
1 parent bd5a9da commit dcb982c
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 5 deletions.
4 changes: 4 additions & 0 deletions README.md
Expand Up @@ -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
Expand Down
16 changes: 12 additions & 4 deletions pkg/codegen/extension.go
Expand Up @@ -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) {
Expand Down
10 changes: 9 additions & 1 deletion pkg/codegen/schema.go
Expand Up @@ -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
Expand Down

0 comments on commit dcb982c

Please sign in to comment.