📖 2 min read (~ 400 words).

Naming from struct tags

By default codescan derives a field’s spec name from its json: tag (then the Go field name). Options.NameFromTags lets you choose which struct-tag types supply the name, in precedence order — handy when your structs are tagged for another binding library (for example gin’s form:). It applies everywhere a name is derived from a field: schema properties, parameters, and response headers. The model below tags every field with both json: and form::

// Filter is a query model whose fields carry both json: and form: tags.
//
// swagger:model
type Filter struct {
	// SortKey selects the sort column.
	SortKey string `json:"sortKey" form:"sort_key"`

	// PageSize bounds the page length.
	PageSize int `json:"pageSize" form:"page_size"`
}

Full source: docs/examples/shaping/naming-from-tags/naming.go

Scanned with the default (["json"]) and with ["form","json"], the property names differ — form: wins because it is listed first:

Default (json)
{
  "type": "object",
  "title": "Filter is a query model whose fields carry both json: and form: tags.",
  "properties": {
    "pageSize": {
      "description": "PageSize bounds the page length.",
      "type": "integer",
      "format": "int64",
      "x-go-name": "PageSize"
    },
    "sortKey": {
      "description": "SortKey selects the sort column.",
      "type": "string",
      "x-go-name": "SortKey"
    }
  },
  "x-go-package": "github.com/go-openapi/codescan/docs/examples/shaping/naming-from-tags"
}

Full source: docs/examples/shaping/naming-from-tags/testdata/default.json

NameFromTags: [form, json]
{
  "type": "object",
  "title": "Filter is a query model whose fields carry both json: and form: tags.",
  "properties": {
    "page_size": {
      "description": "PageSize bounds the page length.",
      "type": "integer",
      "format": "int64",
      "x-go-name": "PageSize"
    },
    "sort_key": {
      "description": "SortKey selects the sort column.",
      "type": "string",
      "x-go-name": "SortKey"
    }
  },
  "x-go-package": "github.com/go-openapi/codescan/docs/examples/shaping/naming-from-tags"
}

Full source: docs/examples/shaping/naming-from-tags/testdata/form.json

codescan.Run(&codescan.Options{
    Packages:     []string{"./..."},
    ScanModels:   true,
    NameFromTags: []string{"form", "json"},
})

The first listed tag that supplies a usable name wins; a tag that is absent or carries only options (e.g. ,omitempty) is skipped and the next is tried. An explicit empty list (NameFromTags: []string{}) consults no tag and falls back to the Go field name.

Info

Name only. NameFromTags changes only the name. The encoding/json directives — json:"-" (exclude), ,omitempty, ,string — are always read from the json tag, whatever names the field. Targeted renames (the name: keyword, swagger:name, and swagger:model {name}) still take precedence over any tag-derived name.